Remove last N lines from a text file in Linux
+3
−0
How can I delete a specific number of lines from the end of a text file using Linux command-line tools?
2 answers
+3
−0
Use head to keep all but the last N lines, overwriting the file:
head -n -N input.txt > tmp && mv tmp input.txt
Example: remove last 3 lines
head -n -3 file.txt > tmp && mv tmp file.txt
If you want in-place editing without a temp file. The command
sed -i "$(($(wc -l < file)-22)),\$d" file
is used to delete the last 22 lines from a file named file.
+1
−0
To delete $n lines in-place (won't break hard-links):
printf ',$-%dw\n' $n | ed -s file
Exits with a non-zero value if the change failed (e.g. not enough lines in file).

0 comment threads