Quick Unix command to print non-contiguous lines from a text file? Quick Unix command to print non-contiguous lines from a text file? shell shell

Quick Unix command to print non-contiguous lines from a text file?


You can ask for specific lines by number like this:

sed -n '1p;5p;7p' my_file

The -n flag means, "don't print lines by default", and then for each line you want, you specify the line number and the p (print) command.


$ awk -v lines="2 4 7" 'index(" "lines" "," "NR" ")' file  BobDaphneHeather$ awk -v lines="3 5" 'index(" "lines" "," "NR" ")' file  CarlErwin

The blank chars around lines and NR in the above are necessary so that NR value 9 doesn't match when lines contains 19, for example.

If you don't mind hard-coding the line numbers inside the script you could alternatively do:

awk 'NR~/^(2|4|7)$/' file


Dynamically generate the sed program:

store the lines you want in an array:

$ lines=(2 5 7)$ sed -n "$(printf "%dp;" "${lines[@]}")" fileBobErwinHeather

or if the line numbers are in a file:

$ sed -n "$(sed 's/$/p/' numbers)" file