Friday, February 10, 2012

Print 3 lines before and 5 lines after pattern match abcd in a file a.txt

In Linux:

awk 'c-->0;$0~s{if(b)for(c=b+1;c>1;c--)print r[(NR-c+1)%b];print;c=a}b{r[NR%b]=$0}' b=3 a=5 s="abcd" a.txt

In SOLARIS:

nawk 'c-->0;$0~s{if(b)for(c=b+1;c>1;c--)print r[(NR-c+1)%b];print;c=a}b{r[NR%b]=$0}' b=3 a=5 s="abcd" a.txt

ftp in UNIX

ftp -n 10.200.120.12 << EOF
quote user username
quote pass password
cd /path/to/directory/
prompt off
put dump.txt
exit
EOF

Friday, August 19, 2011

Adding 30 days to current date using PERL inside SHELL


#! /usr/bin/ksh

dt1=`perl -l -e '$date=(localtime(time + (30 * 24 * 60 *60))); print $date;'`

dt=`echo $dt1|awk '{if($3<10) print $1" "$2" 0"$3" "$4" "$5;else print $0}'`

echo $dt|awk '{print $5"-"$2"-"$3"23:59:59"}'|sed -e 's/Jan/01/g'\;'s/Feb/02/g'\;'s/Mar/03/g'\;'s/Apr/04/g'\;'s/May/05/g'\;'s/Jun/06/g'\;'s/Jul/07/g'\;'s/Aug/08/g'\;'s/Sep/09/g'\;'s/Oct/10/g'\;'s/Nov/11/g'\;'s/Dec/12/g'

Print 3 lines before pattern match using sed and awk ..


To reverse a file using awk and print next three lines after pattern match (Including pattern):

awk '{ a[i++] = $0 } END { for (j=i-1; j>=0;) print a[j--] }' abcd.txt |sed -n '/MANU/{p;n;p;n;p;n;p;}' >abcd_new.txt

(This can be used when you want to print 3 lines before pattern match, including pattern. Logic: reverse a file and print 3 lines after pattern match.)

How to reverse a file using awk:

awk '{ a[i++] = $0 } END { for (j=i-1; j>=0;) print a[j--] }' abcd.txt

How to reverse a file using sed:

sed -n '1!G;h;$p' abcd.txt

Tuesday, November 23, 2010

Adding one month (30-31 days) in UNIX SOLARIS


#! /usr/bin/ksh
d=`date +%d`
m=`date +%m`
y=`date +%Y`
if [ $m%2 -eq 0 ]
then
d1=`expr $d + 30`
d=expr $d1 - 30`
else
d1=`expr $d + 31`
d=expr $d1 - 31`
fi
if [ $m -eq 12 ]
then
y=`expr $y + 1`
m=0
fi
m=`expr $m + 1`
if [ $m -lt 10 ]
then
m=0$m
fi
echo "$y-$m-$d"
exit 0

Monday, June 14, 2010

sort a delimited file on the basis of a column

sort -t":" -k3 filename.txt

(The above will sort a file filename.txt which is ":" delimited on the basis of third column.)