How to Use sed to Insert String After Every N Lines


Often you may want to use sed to insert a string after every N lines in a file.

You can use the following basic syntax to do so:

sed '0~3 s/$/\nSTRING/g' cities.txt

This particular example inserts “STRING” after every three lines in the file named cities.txt.

Note that we use the syntax first~step to perform some action on the first line specified, followed by every nth line specified by the number for step.

Since there is no line 0, the first string is inserted after line 3, then on every third line after it in the file.

Note that we used \n to force the new string to be placed on a new line. Feel free to leave this out if you’d like the new string to simply be appended to the end of the existing line.

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

Example: Use sed to Insert String After Every N Lines

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

Suppose that we would like to insert “STRING” after every third line in the file.

We can use the following syntax to do so:

sed '0~3 s/$/\nSTRING/g' cities.txt

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

sed insert string after every N lines

Notice that a new line with the text “STRING” has been inserted after every three lines in the file.

Note that you could also use the > command to save these changes to a new file:

sed '0~3 s/$/\nSTRING/g' cities.txt > cities_new.txt

This particular example would insert “STRING” after every third line in 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 Insert a Line After Match
How to Use sed to Insert Empty Line in a File
How to Use sed to Insert Line with Leading Spaces
How to Use sed to Insert Line at Specific Line Number

Leave a Reply