Negative arguments to head / tail
You can remove the first 12 lines with:
tail -n +13
(That means print from the 13th line.)
Some implementations of head
like GNU head
support:
head -n -12
but that's not standard.
tail -r file | tail -n +12 | tail -r
would work on those systems that have tail -r
(see also GNU tac
) but is sub-optimal.
Where n
is 1:
sed '$d' file
You can also do:
sed '$d' file | sed '$d'
to remove 2 lines, but that's not optimal.
You can do:
sed -ne :1 -e 'N;1,12b1' -e 'P;D'
But beware that won't work with large values of n with some sed
implementations.
With awk
:
awk -v n=12 'NR>n{print line[NR%n]};{line[NR%n]=$0}'
To remove m
lines from the beginning and n
from the end:
awk -v m=6 -v n=12 'NR<=m{next};NR>n+m{print line[NR%n]};{line[NR%n]=$0}'
You can use the following way to remove first N lines and last M lines.
With N=5
, M=7
and file test.txt
:
sed -n -e "6,$(($(wc -l < test.txt) - 7))p" test.txt
The command prints all lines from N+1 to LastLine-M.
Another option is to use python:
python -c 'import sys;print "".join(sys.stdin.readlines()[5:-7]),' < test.txt