Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 940
ScaryAardvark Avatar asked Feb 10 '10 14:02

ScaryAardvark


People also ask

How do I print a range of lines?

Printing given range of lines using sed-n option is to print 'n' number of lines. in above example 'p' is used to Print the current pattern space. Same as above we can also use 'd' Delete pattern space.

How do you print a range of lines in Unix?

p - Print out the pattern space (to the standard output). This command is usually only used in conjunction with the -n command-line option. n - If auto-print is not disabled, print the pattern space, then, regardless, replace the pattern space with the next line of input.

How do I grep specific lines in a file?

The grep command searches through the file, looking for matches to the pattern specified. To use it type grep , then the pattern we're searching for and finally the name of the file (or files) we're searching in. The output is the three lines in the file that contain the letters 'not'.

How will you find last 10 lines of file?

Use the tail command to write the file specified by the File parameter to standard output beginning at a specified point. This displays the last 10 lines of the accounts file. The tail command continues to display lines as they are added to the accounts file.


1 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 
like image 108
Alok Singhal Avatar answered Nov 05 '22 03:11

Alok Singhal