Remove Last N Lines From File in Linux

Remove Last N Lines From File in Linux

In Linux, there are commands that allows to perform various operations on files. Sometimes we may need to remove last N lines from file in Linux. This tutorial demonstrates how to do that.

For testing purpose, create a new file:

printf "Line1\nLine2\nLine3\nLine4\nLine5\nLine6\nLine7\n" > test.txt

The head command is commonly used to print first N lines from file. The -n option allows to specify number of the lines to print. We can provide negative number. It means that last N lines will be ignored. Using > redirection operator, command output can be written to file.

For example, to remove the last 4 lines from file, run the following command:

head -n -4 test.txt > tmp.txt && mv tmp.txt test.txt

Firstly, output is written to temporary file and after that file is renamed.

Leave a Comment

Cancel reply

Your email address will not be published.