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?
1 answer
+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.

0 comment threads