简体   繁体   中英

print two lines from multiple files with the file name in awk

I have multiple files in a directory. i want to pull out certain lines from all those files and print to an output file.

File1

line1
line2 
line3
line4

File2

line1
line2 
line3
line4

and like so i have many files. Desired Output

File1
line2
line4
File2
line2
line4

I tried

awk 'FNR==2 {print FILENAME, $0}' *.txt

This prints just line 2. I also tried with FNR==2 & 4 How do i print two lines here? Ill appreciate any help!

I think that this is what you want:

awk 'FNR == 1 { print FILENAME } FNR == 2 || FNR == 4' *.txt

At the start of each file, print the filename. Then print, when the line number is 2 or 4.

I think you should modify your command to

awk 'FNR==1{print FILENAME} (FNR==2||FNR==4) {print $0}' *.txt
1.txt
line2 
line4
2.txt
line2 
line4

Just for fun if you have GNU sed

$ sed -sn '1F;2p;4p' *.txt
file1.txt
line2 
line4
file2.txt
line2 
line4
  • -s to treat input files separately so that they each have their own addressing
  • -n disable automatic printing
  • 1F print filename if line number is one
  • 2p;4p print 2nd and 4th line

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM