How to Use sed to Print Every nth Line of File


Often you may want to use sed to print every nth line from a file.

You can use the following syntax to do so:

sed -n '0~3p' cities.txt > cities_new.txt

This particular example will print every third line from the file named cities.txt and save the results to a new file named cities_new.txt.

This uses the sed syntax first~step, which prints the line specified by the number for first, followed by every nth line specified by the number for step.

There is no line 0, so this effectively prints every third line of the file.

If you would instead like to print the first line of the file, followed by every third line after that, then you could specify a value of 1 in the first~step syntax:

sed -n '1~3p' cities.txt > cities_new.txt

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

Example: Use sed to Print Every nth Line of File

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

Suppose that we would like to print every third line of the file and save the results to a new file named cities_new.txt.

We can use the following syntax to do so:

sed -n '0~3p' cities.txt > cities_new.txt

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

sed print every nth line of file

Notice that when we use the cat command to view the contents of cities_new.txt we can see that it contains every third line from the original cities.txt file.

We could also use the following syntax to print the first line of the file, followed by every third line after that:

sed -n '1~3p' cities.txt > cities_new.txt

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

sed print every nth line of file including first line

When we use the cat command to view the contents of cities_new.txt we can see that it contains every third line from the original cities.txt file, starting from the first line of the file.

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