Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I extract a predetermined range of lines from a text file on Unix?

I have a ~23000 line SQL dump containing several databases worth of data. I need to extract a certain section of this file (i.e. the data for a single database) and place it in a new file. I know both the start and end line numbers of the data that I want.

Does anyone know a Unix command (or series of commands) to extract all lines from a file between say line 16224 and 16482 and then redirect them into a new file?

like image 819
Adam J. Forster Avatar asked Sep 17 '08 13:09

Adam J. Forster


People also ask

How do I print a range of lines in Linux?

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. Start next cycle.


2 Answers

sed -n '16224,16482p;16483q' filename > newfile 

From the sed manual:

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. If there is no more input then sed exits without processing any more commands.

q - Exit sed without processing any more commands or input. Note that the current pattern space is printed if auto-print is not disabled with the -n option.

and

Addresses in a sed script can be in any of the following forms:

number Specifying a line number will match only that line in the input.

An address range can be specified by specifying two addresses separated by a comma (,). An address range matches lines starting from where the first address matches, and continues until the second address matches (inclusively).

like image 122
boxxar Avatar answered Sep 19 '22 11:09

boxxar


sed -n '16224,16482 p' orig-data-file > new-file 

Where 16224,16482 are the start line number and end line number, inclusive. This is 1-indexed. -n suppresses echoing the input as output, which you clearly don't want; the numbers indicate the range of lines to make the following command operate on; the command p prints out the relevant lines.

like image 21
JXG Avatar answered Sep 16 '22 11:09

JXG