# Use sed to Insert Text Every 'n' Lines/Characters

There are a lot of overly complicated ways to insert a line after every nth line, but the simplest way I find is the following:

``````sed '0~3 s/\$/\nMy Text/g' < input.file
``````

In a file with six lines you get something like the following:

``````Line 1
Line 2
Line 3
My Text
Line 4
Line 5
Line 6
My Text
``````

Just swap the second half of `0~3` with the number of lines after which you want to insert to adjust where you insert your text, e.g. `0~30` will insert every 30th line.

The first digit of the `0~3` specifies the first line the insertion should happen (with `0` not prepending to the beginning of the file):

``````sed '2~3 s/\$/\nMy Text/g' < input.file
Line 1
Line 2
My Text
Line 3
Line 4
Line 5
My Text
Line 6
``````

To insert something every nth character the syntax is a bit different:

``````sed 's/.\{2\}/&#/g'
``````

Will insert a `#` every 2 characters:

``````Li#ne# 1#
Li#ne# 2#
Li#ne# 3#
Li#ne# 4#
Li#ne# 5#
Li#ne# 6#
``````

Swap out the 2 for the desired number of characters.