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!

How to print previous 3 lines once search found ? 2

Status
Not open for further replies.

lotamoka

MIS
Jul 15, 2007
43
US
Hi
I have file like ..
cbdstsm1
brwstsm1
brwstsm2
sbdsc2
andscjk
test
maning
Is there awk command to print previous 3 lines once search finds test ?

Output like ..

brwstsm2
sbdsc2
andscjk
test
 
You may find grep -B3 test inputfile more convenient, if you have a grep that supports -B.

Failing that:

[tt]awk '/test/ { for (i=(NR-3); i<NR; i++) { print b[i%3] }; print } { b[NR%3]=$0 }' inputfile[/tt]

Annihilannic.
 
Annihilannic,
may ask a similar question:

I read your solution above using awk, and I wander if you could adapt it to my need, which differs as following:

- need to process all files with filenames like "filename*" in the current directory
- need to extract line containing pattern, plus following 5 lines

in grep terms: grep "pattern containing spaces" filename*
but my grep does not apprear to have options for extracting the context of the matching line.

The background to this is:
I need to produce a list of programs (files) that are able to modify a given table(indicated by the search pattern). The particular language defines access to table on several subsequent lines of code. I would need grep to search on "pattern", and extract the record containg the pattern, followed by say the next 5 records.

then I can visually scan the output and determine which programs will modify the table, given that words like 'write', 'rewrite' 'delete' etc will be present.

Cheers
 
What about this ?
awk 'FNR==1{f=0}/pattern containing spaces/{f=6}f{print;--f}' filename*

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
PHV,
Thanks for the quick answer, seems to be doing something, the only problem is that I cannot interprete the output: I would need the file names to also be displayed, either preceeding, or on the same line, for each chunk of lines being extracted; at the moment I cannot determine from the output which lines belong under which file. Is there a solution to the issue?

Cheers
 
Either preceeding:
awk 'FNR==1{f=0}/pattern containing spaces/{f=6;print FILENAME}f{print;--f}' filename*

or on the same line:
awk 'FNR==1{f=0}/pattern containing spaces/{f=6}f{print FILENAME,$0;--f}' filename*

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

Did you try grep?
Code:
grep -B 3 'test' inputfile
grep -A 5 'pattern with spaces' filename*
[3eyes]


----------------------------------------------------------------------------
The person who says it can't be done should not interrupt the person doing it. -- Chinese proverb
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top