bashtext-processing

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?


Solution

  • 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).