Print A Specific Block Of Lines From A File In Linux

Tuesday, May 20, 2014 - 21:08

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

Category: 
Tags: 
philipnorton42's picture

Philip Norton

Phil is the founder and administrator of #! code and is an IT professional working in the North West of the UK.
Google+ | Twitter

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.

Add new comment