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

pattern matching and print filename

Status
Not open for further replies.

alexbotea2005

Technical User
Nov 4, 2010
4
Code:
 awk '/ pattern/ {show[NR+2]++}  show[NR]' *.txt

The above code search for pattern in several text files and when pattern is found than prints the 2'nd row after.
How do I add the filename to be printed in the same line with the pattern?

Thanks in advance
 
Hi

Not sure what you mean by "in the same line with the pattern". The pattern is never printed there.
Code:
awk '[fuchsia]/ pattern/[/fuchsia] [teal]{[/teal]show[teal][[/teal][blue]NR[/blue][teal]+[/teal][purple]2[/purple][teal]]++[/teal][teal]}[/teal] show[teal][[/teal][blue]NR[/blue][teal]][/teal] [highlight][teal]{[/teal][COLOR=chocolate]print[/color] [blue]FILENAME[/blue][teal],[/teal][navy]$0[/navy][teal]}[/teal][/highlight]' *.txt
Tested with [tt]gawk[/tt] and [tt]mawk[/tt].


Feherke.
[link feherke.github.com/][/url]
 
Thank you for your respond,
Yes you are right not the pattern gets diplayed, it get displayed the 2'nd row after matching the pattern.
The script works fine, I need only a small tweak if it's possible. The filename get's duplicated as follows:
Code:
file1.txt 0
file1.txt 2'nd row after pattern
file2.txt 0
file2.txt 2'nd row after pattern
file3.txt 0
file3.txt 2'nd row after pattern
 
Hi

Not for me. Tell us which Awk implementation are you using and show some exact sample input for which the duplication occurs.

Feherke.
[link feherke.github.com/][/url]
 
Hi,
Please find bellow the input files:
Code:
$ cat file1.txt
 10%  20% 30%
|      |      |
transfered 35168 bytes

$ cat file2.txt
 10%  20% 30%
|      |      |
transfered 435168 bytes

$ cat file3.txt
 10%  20% 30%
|      |      |
transfered 568 bytes

$ cat file4.txt
 10%  20% 30%
|      |      |
transfered 18168 bytes

The script result is:
Code:
$ awk '/ 10%  20% 30%/ {print FILENAME , show[NR+2]++}  show[NR] {print FILENAME , $0}' *.txt
file1.txt 0
file1.txt transfered 35168 bytes
file2.txt 0
file2.txt transfered 435168 bytes
file3.txt 0
file3.txt transfered 568 bytes
file4.txt 0
file4.txt transfered 18168 bytes


I'm using :
Code:
$ awk -W version
GNU Awk 4.0.1
Copyright (C) 1989, 1991-2012 Free Software Foundation.

Many Thanks
 
Hi

That is not the code I posted. If you not want to have [tt]FILENAME[/tt] printed twice, then why you added the extra [tt]print FILENAME[/tt] ?

Feherke.
[link feherke.github.com/][/url]
 
Sorry for that, the first print was part of my trials,
Thank you for you help.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top