How to Use sed to Remove Every Other Line in File


Often you may want to use sed to remove every other line in a file.

You can use the following syntax to do so:

sed '1~2d' cities.txt

This particular example will remove every other line from the file named cities.txt, starting with the first line in the file.

This example uses the sed d command along with the syntax first~step to delete the line specified by the number for first, followed by every nth line specified by the number for step.

If you would like to remove every other line from the file, starting with the second line in the file, then you can specify a value of 2 for the first argument instead:

sed '2~2d' cities.txt 

The following example shows how to use this syntax in practice.

Example: Use sed to Delete Ever Other Line in File

Suppose we have a file named cities.txt that contains the names of various U.S. cities:

Suppose that we would like to delete every other line in the file, starting with the first line.

We can use the following syntax to do so:

sed '1~2d' cities.txt

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

sed remove every other line from file

Notice that every other line in the file has been deleted, starting with the first line.

Supposed instead that we would like to delete every other line in the file, starting with the second line.

We can use the following syntax to do so:

sed '2~2d' cities.txt

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

sed remove every other line from file, starting with second line

Notice that every other line in the file has been deleted, starting with the second line.

Also note that you could use the > command to save these results to a new file if you’d like:

sed '1~2d' cities.txt > cities_new.txt

This would remove every other line from the file named cities.txt and save the results to a new file named cities_new.txt.

Related Tutorials

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

How to Use sed to Print Out Line Numbers
How to Use sed to Print Specific Lines in File
How to Use sed to Insert Line at Specific Line Number
How to Use sed to Extract All Lines Containing a Pattern

Leave a Reply