Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

print the 2nd line above the pattern 2

Status
Not open for further replies.

frankli

Technical User
Apr 6, 2005
44
CA
Just wandering if there is a easy way in awk to print the 2nd line above the pattern line

abc
def
hij
klm

locate klm to print out def.

Thanks in advance to my favorite AWK list!
 
A starting point:
Code:
awk '{a[NR%3]=$0}/klm/{print a[(NR-2)%3]}' /path/to/input

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
Hi PH,

It works. Thanks.

I also tried below it works too, please give a tip on how to understand NR%3

awk '{a[NR]=$0}/klm/{print a[NR-2]}' /path/to/input


Regards,
-frank

PS. Would like to know the thought of retrive 2nd line below the patten line too .. just came up ... Thanks.
 
Your solution may choke on huge input file (memory exhausted)
My solution stores only 3 lines of data.

BTW, NR%3 stands for NR modulo 3.

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
following above thought I want to print the 2nd line below the pattern line but I can only pick up the 1st match line not all of them ... something is wrong please comment,

abc
def
ghi
jkl
mno
pqr
stu
abc
vwx
yza

use abc to print ghi, yza,

but I only get ghi use below ...

awk '{a[NR]=$0} /abc/ {b[NR]=NR+2} END {for (i in b); {print a[b]}}' input/file

Thanks!



 
below will print all the match line for above case ... but can not handle the memory choking ...

awk '{a[NR]=$0} /abc/ {b[NR]=NR+2} END {for (i in b) if (i != null) {print a[b]}}' input/file

 
How about:

Code:
awk '/abc/ { getline; getline; print }'

Or:

Code:
awk '/abc/ { found=NR } NR==found+2'

Annihilannic.
 
Thanks Annihilannic.

Just FYI, for the 2nd option, if there is more than one line above the pattern line it will give out wrong output,

Try it against below

123
456
abc
def
ghi
jkl
mno
pqr
stu
abc
vwx
yza

the output of "awk '/abc/ { found=NR } NR==found+2'" would be

456
ghi
yza

 
awk '/abc/ { found=NR } found && NR==found+2

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top