Do something every nth line in a file using Linux Bash

Home > Search
  by

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

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter in the box below so that we can be sure you are a human.




Comments