Print A Specific Block Of Lines From A File In Linux

If you have a large file of data that you are trying to import, or a log file you are trying to dissect then you'll rarely want to print it directly out to the screen. Using commands like more or programs like vim can make things a little easier but you still have to run through potentially thousands of lines to find the correct block.

To load a few specific lines from a file you can use a combination of the head and tail commands. The following command will print out lines 200 to 220 from a large file called 'bigfile. The head command will print out the first 220 lines from a file, which is then piped into a tail command that prints out only the last 20 lines of the output generated by the previous command.

head -n 220 bigfile | tail -n 21

Alternatively, you can use sed to print out the same block from the large file.

sed -n 200,220p bigfile

Using sed is probably a better approach as it uses a single command to produce the output. The problem with piping the output of head into tail is that the head command will pass all of the lines it finds into the tail command, which can use up a lot of memory (depending on the file size of course).

Comments

I simply wanted to write down a quick word to say thanks to you for those wonderful tips and hints you are showing on this site.
Permalink

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
3 + 8 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.