Thomas' Tech Tips

Print all except the first and last few lines of a file

6 November 2022 - Thomas Damgaard

I recently needed to cut the first N lines of output from a command as well as. the last M lines of the command.

This is easily done using head and tail:

Print all except the first 2 lines:

$ seq 10 | tail -n+2
2
3
4
5
6
7
8
9
10

Print all except the last 2 lines:

seq 10 |head -n-2
1
2
3
4
5
6
7
8

And in combination: print all except the first two and the last two lines:

$ seq 10 | tail -n+2 |head -n-2
2
3
4
5
6
7
8
Filed under: howto, linux, shell, tips

Back to article list