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 gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

printing lines before and after a match

Status
Not open for further replies.

aqnjrtek

Technical User
Apr 5, 2006
3
US
Hello!!!

I am an awk newbie. I just want to know how to print the whole range of 19 lines before and 26 lines after a match.

I used

awk '{if ($1=="pattern" && $2>0) print}' input.file

I got all that matched but I need the match plus 19 lines before it and 26 lines after it.

Thanks a lot!!!

aqnjrtek
 
Hi

Of course, you can do it also with [tt]awk[/tt] :
Code:
awk '/pattern/{for(i=0;i<19;i++)print a[i];print;for(i=0;i<26;i++){getline;print}}{a[NR%19]=$0}' input.file

Feherke.
 
Hi

Sorry. The morning coffee does not make its effect yet.
Code:
awk '/pattern/{for(i=0;i<19;i++)print a[[red]([/red]i[red]+NR)%19[/red]];print;for(i=0;i<26;i++){getline;print}}{a[NR%19]=$0}' input.file

Feherke.
 
Thanks a lot for these suggestions. I will try both of them. I also tried to use both awk and R and it worked but these two suggestions are concise and seem to be better. Wow!
 
Oh, by the way. With these scripts, how do I include the fact that the second column should be >0 for it to be a match --- for both grep and awk commands? Thanks!!!
 
Hi

You already had the [tt]awk[/tt] solution in your question. And with [tt]grep[/tt] is abit ugly, but simple.
Code:
grep -E -B 19 -A 26 "^pattern +[1-9]" input.file
[gray]# or[/gray]
awk '$1=="pattern" && $2>0{for(i=0;i<19;i++)print a[(i+NR)%19];print;for(i=0;i<26;i++){getline;print}}{a[NR%19]=$0}' input.file
( Note, that I supposed that the fields are delimited by one or more spaces. )

Feherke.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top