How can I read first n and last n lines from a file?

Amir picture Amir · Feb 19, 2015 · Viewed 14k times · Source

How can I read the first n lines and the last n lines of a file?

For n=2, I read online that (head -n2 && tail -n2) would work, but it doesn't.

$ cat x
1
2
3
4
5
$ cat x | (head -n2 && tail -n2)
1
2

The expected output for n=2 would be:

1
2
4
5

Answer

srd picture srd · Feb 19, 2015
head -n2 file && tail -n2 file