Using head and tail to grab different sets of lines and saving into same file

headtail

So this is for homework, but I will not be asking the specific homework question.

I need to use head and tail to grab different sets of line from one file. So like lines 6-11 and lines 19-24 and save them both to another file.
I know I can do this using append such as

head -11 file|tail -6 > file1; head -24 file| tail -6 >> file1. 

But I don't think we are supposed to.
Is there a specific way I could combine the head and tail commands and then save to the file?

Best Answer

You can do it with head alone and basic arithmetic, if you group commands with { ... ; } using a construct like

{ head -n ...; head -n ...; ...; } < input_file > output_file

where all commands share the same input (thanks @mikeserv).
Getting lines 6-11 and lines 19-24 is equivalent to:

head -n 5 >/dev/null  # dump the first 5 lines to `/dev/null` then
head -n 6             # print the next 6 lines (i.e. from 6 to 11) then
head -n 7 >/dev/null  # dump the next 7 lines to `/dev/null` ( from 12 to 18)
head -n 6             # then print the next 6 lines (19 up to 24)

So, basically, you would run:

{ head -n 5 >/dev/null; head -n 6; head -n 7 >/dev/null; head -n 6; } < input_file > output_file
Related Question