Another.Chemist Another.Chemist - 1 year ago 73
Bash Question

Print a range of lines by line numbers across multiple files

For example:

Print all between two lines in sed is:

sed -n '30,40p' filename

But, when I use it as:

sed -n '30,40p' *

It only prints the lines between 30 and 40 of the first file.

What about a bunch of files?

Answer Source

Per POSIX, sed doesn't reset line numbering across input files.
(If you have GNU sed, you can use the -s option - see bottom).

While you could use a shell loop to address this problem (for f in *; sed ...; done), it's more efficient to use a single awk command, where built-in variable FNR reflects the input file-relative line number (1-based):

awk -v from=30 -v to=40 'FNR >= from && FNR <= to' *

This solution is POSIX-compliant.

If you have GNU sed, use the -s option to restart line numbering for each input file:

sed -s -n '30,40p' *
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download