Hi all , i need to grep for a string in a text file and print the string and the 3rd line above it.
As always , Thanks.
Hi all , i need to grep for a string in a text file and print the string and the 3rd line above it.
As always , Thanks.
If your sed version supports the -B option:
grep -B 3 '<string>' file | sed '2,3d'
Otherwise with awk:
awk 'NR==FNR{if(/<string>/){n=NR;next}}FNR==n-3||/<string>/' file1 file1
Thanks Franklin for yr quick resp, the sed version i have does not support -B option. I tried the awk option and i have trouble in the output of the above command. It prints all occurances of the string i grep for but i am not getting the 3rd line except for the last occurance.
For eg , the sample file would be something like below , i need to grep for 103 and then print the 3rd line above it.
Seqnumber xxxxx
This is line one of a
This is line one of a
This is line 1103 two of a
Seqnumber xxxxx
This is line one of a
This is line one of a
This is line 103 four of a
Seqnumber xxxxx
This is line one of a
This is line one of a
This is line 15603 four of a
Seqnumber xxxxx
This is line one of a
This is line one of a
This is line 103 four of a
Seqnumber xxxxx
This is line one of a
This is line one of a
This is line 1345 four of a
Seqnumber xxxxx
This is line one of a
This is line one of a
This is line 103 four of a
Thanks again.
My thought was that there was just one occurrence of the pattern, try this one:
awk '{a[NR%4]=$0}/ 103 /{print a[(NR+1)%4];print}' file
Use nawk or /usr/xpg4/bin/awk on Solaris.
Regards
Sweet , thats works like a champ. Thanks Franklin.
I am glad i found this forum.