开发者

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 actua开发者_运维技巧lly Solaris so gnu flavour isn't available).

Thx


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"


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.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜