Get a range of lines from a file given the start and end line numbers

Viewed 29816

I need to extract a set number of lines from a file given the start line number and end line number.

How could I quickly do this under unix (it's actually Solaris so gnu flavour isn't available).

Thx

4 Answers

To print lines 6-10:

sed -n '6,10p' file

If the file is huge, and the end line number is small compared to the number of lines, you can make it more efficient by:

sed -n '10q;6,10p' file

From testing a file with a fairly large number of lines:

$ wc -l test.txt 
368048 test.txt
$ du -k test.txt 
24640    test.txt
$ time sed -n '10q;6,10p' test.txt >/dev/null
real   0m0.005s
user   0m0.001s
sys    0m0.003s
$ time sed -n '6,10p' test.txt >/dev/null
real   0m0.123s
user   0m0.092s
sys    0m0.030s

Or

head -n "$last" file | tail -n +"$first"

you can do it with nawk as well

#!/bin/sh
start=10
end=20
nawk -vs="$start" -ve="$end" 'NR>e{exit}NR>=s' file
Related