ScaryAardvark
ScaryAardvark

Reputation: 2965

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

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

Upvotes: 22

Views: 32110

Answers (4)

Robert Massaioli
Robert Massaioli

Reputation: 13487

I wrote a Haskell program called splitter that does exactly this: have a read through my release blog post.

You can use the program as follows:

$ cat somefile | splitter 4,6-10,50-

That will get lines four, six to ten and lines fifty onwards. And that is all that there is to it. You will need Haskell to install it. Just:

$ cabal install splitter

And you are done. I hope that you find this program useful.

Upvotes: 1

martinwguy
martinwguy

Reputation: 972

Or

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

Upvotes: 1

Alok Singhal
Alok Singhal

Reputation: 96191

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

Upvotes: 56

ghostdog74
ghostdog74

Reputation: 342649

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

Upvotes: 0

Related Questions