Text Processing – Print Specific Line from Multiple Files

awksedshell-scripttext processing

I have a collection of 5000+ files and I just want to create an output.txt file which contains the 27th line of all the files, along with their filenames.
What I got from the internet is picking specific line from a single file using awk or sed commands, such as:
$sed -n 27p *.txt >>output.txt

for example my files in a directory are:

log_1.txt
log_2.txt
log_3.txt
log_4.txt
.
.
.

I want the 27th line of each file with its file name in front or behind of the printed line in the new output.txt file.

Best Answer

 awk 'FNR==27 {print FILENAME, $0}' *.txt >output.txt
  • FILENAME is built-in awk variable for current input file name
  • FNR refer to line number of current file
  • $0 means whole line
Related Question