21

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

Lesmana
  • 24,114
  • 8
  • 78
  • 84
ScaryAardvark
  • 2,773
  • 4
  • 29
  • 41
  • See also: http://stackoverflow.com/questions/1429556/shell-bash-command-to-get-nth-line-of-stdout – Jonathan Leffler Feb 10 '10 at 15:05
  • Possible duplicate of [How can I extract a predetermined range of lines from a text file on Unix?](http://stackoverflow.com/questions/83329/how-can-i-extract-a-predetermined-range-of-lines-from-a-text-file-on-unix) – Lesmana Dec 09 '16 at 16:41

4 Answers4

51

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
Alok Singhal
  • 88,099
  • 18
  • 124
  • 155
1

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.

Robert Massaioli
  • 13,101
  • 7
  • 54
  • 72
1

Or

head -n "$last" file | tail -n +"$first"
martinwguy
  • 928
  • 5
  • 14
0

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
ghostdog74
  • 307,646
  • 55
  • 250
  • 337