4

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.

  • oops.. so much editing. Thanx arzyfex – Ravi Saini Apr 18 '16 at 18:58
12
 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
  • Thanx man this was much better for me. – Ravi Saini Apr 18 '16 at 19:02
2

Using a for loop:

{ for i in *.txt; do echo "$i : $(sed -n '27p' "$i")"; done ;} >output.txt

The for loop may be expensive as you have 5000+ files but given the current hardwares should not be a problem.


Faster way, quitting sed after line 27 (thanks @Fiximan):

{ for i in *.txt; do echo "$i : $(sed -n '27p;q' "$i")"; done ;} >output.txt
  • 2
    Would you need a '27p;q' to be faster or will sed quit automatically after hitting line 27? – Fiximan Apr 18 '16 at 12:33
  • @Fiximan yes that will be quicker – 123 Apr 18 '16 at 13:08
  • @Fiximan That surely would..edited..thanks.. – heemayl Apr 18 '16 at 13:11
  • @Fiximan - sed would quit so quick that it won't print anything... – don_crissti Jan 30 at 18:47
2

Another possibility is :

for i in * ; do echo -n $i" : "  ; head -n 27 "$i" | tail -n 1 ; done > output.txt
0

Simple awk usage:

awk 'FNR==27 {print FILENAME,$0}' /path/to/files/log_*.txt > outfile.txt

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.