How to Use sed to Delete Specific Line Numbers from File


Often you may want to use sed to delete specific line numbers from a file.

You can use the following methods to do so:

Method 1: Delete One Specific Line Number from File

sed -i '4d' cities.txt

This particular example will delete line number 4 from the file named cities.txt.

Method 2: Delete Multiple Specific Line Numbers from File

sed -i '4d;7d;9d' cities.txt

This particular example will delete line numbers 4, 7 and 9 from the file named cities.txt.

Method 3: Delete A Range of Line Numbers from File

sed -i '4,7d' cities.txt

This particular example will delete line numbers 4 through 7 (including 4 and 7) from the file named cities.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

Note: If you simply want to delete specific line numbers and show the resulting output then you can leave out the -i flag.

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 One Specific Line Number from File

We can use the following syntax to delete line number 4 from the file named cities.txt:

sed -i '4d' cities.txt

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

sed delete specific line number

Notice that when we use the cat command again to view the contents of the file that the city on line number 4 (Sacramento) has been deleted from the file.

Example 2: Use sed to Delete Multiple Specific Line Numbers from File

We can use the following syntax to delete line numbers 4, 7 and 9 from the file named cities.txt:

sed -i '4d;7d;9d' cities.txt

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

sed delete multiple line numbers from file

Notice that when we use the cat command again to view the contents of the file that the cities on line numbers 4 (Sacramento), 7 (Memphis) and 9 (Chicago) have all been deleted from the file.

Example 3: Use sed to Delete Range of Line Numbers from File

We can use the following syntax to delete line numbers 4 through 7 from the file named cities.txt:

sed -i '4,7d' cities.txt

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

sed delete range of line numbers from file

Notice that when we use the cat command again to view the contents of the file that the cities on line numbers 4 through 7 have all been deleted from the file.

Related Tutorials

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

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 Extract All Lines Containing a Pattern

Leave a Reply