expert
November 1, 2010, 1:20am
1
Hi,
i would like to get the above and below lines of the grep pattern .
For ex :
file as below:
chk1- aaaa
1-Nov
chk2 -aaaa
##########
chk1-bbbbbb
1-Nov
chk2-bbbbbb
#########
my search pattern is date : 1-Nov
i need the o/p as below
chk1- aaaa
1-Nov
chk2 -aaaa
chk1-bbbbbb
1-Nov
chk2-bbbbbb
Thanks in Advance
$ grep -B1 -A1 1-Nov inputfile
chk1- aaaa
1-Nov
chk2 -aaaa
--
chk1-bbbbbb
1-Nov
chk2-bbbbbb
If your grep doesn't support that option, with awk...
awk '/1-Nov/{print prev"\n"$0;getline;print}{prev=$0}' infile
Try this,
awk '{if(/1-Nov/){print a"\n"$0;getline;print $0} else {a=$0}}' inputfile
expert
November 1, 2010, 2:19am
5
got error :
illegal option -A
illegal option -1
---------- Post updated at 11:49 AM ---------- Previous update was at 11:38 AM ----------
its working .
if i want the below two lines ..
kindly help
awk '/1-Nov/{print prev"\n"$0;getline;print;getline;print}{prev=$0}' infile
grep -C 1 "string" file
To get the same behaviour as grep -A/B/C we need to check if the line exists before printing it:
awk '/string/{if(p)print p;print;if(getline)print}{p=$0}' infile
or
sed -n '/string/{1!x;1!G;$!N;p;};h' infile
Otherwise there is an extra newline or a double last line...