Friday, August 19, 2011

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.)

Tuesday, May 4, 2010

Print every 6th line of a file ..

The below awk command will print every 6th line of a file test.txt starting from line number one.

awk '{if(NR%6==1) print $0}' test.txt

(Note: Print every nth line using awk.)

Sunday, February 14, 2010

Sed Options

use sed when ....

# insert a blank line above every line which matches "regex"
sed '/regex/{x;p;x;}' OR
sed '/regex/{x;G;}'

# insert a blank line below every line which matches "regex"
sed '/regex/G'

# insert a blank line above and below every line which matches "regex"
sed '/regex/{x;p;x;G;}'


# remove the header of a file
sed '/1,1d' filename