1

How can I print specific lines (say the 7th and 15th) of each file in the current directory whose name ends in .txt?

1 Answer 1

3

There are many ways. Here are a few:

  • awk

    awk 'FNR==7 || FNR==15' *.txt
    

    FNR is the line number of the current file. Because the default action in awk when an expression evaluates to true is to print the current line, this will print lines 7 and 15 of each .txt file.

Awk is the only tool I know that can easily (others can do it but not quite so simply) distinguish between the line number of all input and the line number of the current file. Therefore, the other suggestions involve shell loops:

  • sed

    for f in *.txt; do sed -n '7p;15p' "$f"; done
    
  • Perl

    for f in *.txt; do perl -ne 'print if $.==7 or $.==15' "$f"; done
    

    Or, to avoid the shell loop:

    perl -ne '$c++; print if $c==7 or $c==15; $c=0 if eof' *.txt
    
3
  • if i want to print specific lines (say the 7th to 15th) of each file in the current directory whose name ends in .txt? then how can i do @terdon
    – Doe
    Jun 17, 2016 at 16:15
  • @Doe 7th to 15th or 7th and 15th?
    – terdon
    Jun 17, 2016 at 16:43
  • my question was right but i want to know 7 to 15 also thats why i ask you no problem i solve it :) @terdon
    – Doe
    Jun 17, 2016 at 16:53

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .