Bash (Scripting) - do something every nth match

by
Jeremy Canfield |
Updated: March 08 2020
| Bash (Scripting) articles
Let's say file.txt contains the following text.
Hello
World
removeMe
Hello
World
removeMe
Hello
World
removeMe
Hello
World
removeMe
The following sed statement will remove line 3 from the file. This is not what we want, as there are still instances of "removeMe" in the file.
~]# cat file.txt | sed '3d'
Hello
World
Hello
World
removeMe
Hello
World
removeMe
Hello
World
removeMe
With the following sed command, starting at the beginning of the file (line 0), delete every third line.
~]# cat file.txt | sed '0~3d'
Hello
World
Hello
World
Hello
World
Hello
World
In this example, starting at line 0, insert a new line at every third line.
~]# sed -i '0~3 s|$|\n|g' file.txt
removeMe
Hello
World
removeMe
Hello
World
removeMe
Hello
World
removeMe
Hello
World
Did you find this article helpful?
If so, consider buying me a coffee over at