How to Use sed to Delete Last n Lines of File


Often you may want to use sed to delete the last n lines of a file.

You can use the following methods to do so:

Method 1: Delete Last n Lines of File in-place

sed -i "$(($(wc -l < cities.txt)-4+1)),\$d" cities.txt

This particular example will delete the last 4 lines from the file named cities.txt in-place.

To delete a different number of last n lines, simply change the 4 in the code to a different number.

Method 2: Delete Last n Lines of File and Save Results to New File

sed "$(($(wc -l < cities.txt)-4+1)),\$d" cities.txt > cities_new.txt

This particular example will delete the last 4 lines from the file named cities.txt and save the results to a new file named cities_new.txt.

Here are what the various sed commands do:

  • -i deletes the line in the file in-place
  • d is used to delete the line
  • wc -l: counts the number of lines in the file

The following example shows how to use each of these methods in practice with the following file named cities.txt that contains the names of various U.S. cities:

Example 1: Use sed to Delete Last n Lines of File in-place

We can use the following syntax to delete the last 4 lines of the file named cities.txt in-place:

sed -i "$(($(wc -l < cities.txt)-4+1)),\$d" cities.txt

The following screenshot shows how to use this syntax in practice:

sed delete last n lines of file in place

Notice that when we use the cat command again to view the contents of the file that the last 4 lines of the file have been deleted.

Example 2: Use sed to Delete Last n Lines of File and Save Results to New File

We can use the following syntax to delete the last 4 lines of the file named cities.txt and save the results to a new file named cities_new.txt:

sed "$(($(wc -l < cities.txt)-4+1)),\$d" cities.txt > cities_new.txt

The following screenshot shows how to use this syntax in practice:

sed delete last n lines and save results to new file

Notice that when we use the cat command to view the contents of the cities_new.txt file that it contains all lines from the cities.txt file with the last 4 lines removed.

Related Tutorials

The following tutorials explain how to perform other common tasks in sed:

How to Use sed to Delete First n Lines of File
How to Use sed to Delete All Lines Containing Specific String
How to Use sed to Delete All Empty Lines in File
How to Use sed to Delete Specific Line Numbers from File

Leave a Reply