1

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

I Know About 7 and 15 it is done like

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

but if i want to take 7 to 15 then how can i do it?

1 Answer 1

2

Using sed to print 7th to 15th lines of all .txt files in the current directory:

for i in *.txt; do sed -n '7,15 p' "$i"; done

Here 7,15 indicates the line range to print by sed, in this case from 7 to 15.


As you were using awk:

awk 'FNR>=7 && FNR<=15' *.txt

Combination of head and tail:

for i in *.txt; do tail -n +7 "$i" | head -9; done

Or as @steeldriver mentioned, with the newer GNU sed (any supported releases of Ubuntu has it), you can just do:

sed -sn '7,15 p' *.txt

Here -s is to treat each file separately, rather than all of them combined as a single stream.

2
  • Modern versions of GNU sed have a -s (--separate) flag that causes multiple files on the command line to be treated separately - with that, you can just do sed -sn '7,15p' file*.txt instead of using a shell loop Jun 17, 2016 at 17:12
  • @steeldriver Brilliant, was looking for that. Thanks.
    – heemayl
    Jun 17, 2016 at 17:13

You must log in to answer this question.

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