How to replace the nth occurrence of a word using sed

Assume the following scenario, you have a text file and you want to replace each nth occurrence of a word on each line, using sed is a…

How to replace the nth occurrence of a word using sed
Photo by Kristian Strand on Unsplash

Assume the following scenario, you have a text file and you want to replace each nth occurrence of a word on each line, using sed is a straightforward task! follow me to this article to show you how!

Creating the file

Create the following file as file.txt , this file is a two-line file in which each line contains the word apple four times, this file will be used to make our tests

apple apple apple apple 
apple apple apple apple

Replacing each nth occurrence of word on each line

In a terminal enter the following, this replaced the 3rd occurrence of “apple” on each line

$ sed 's/apple/orange/3' file.txt 
apple apple orange apple 
apple apple orange apple

Here is a breakdown of the syntax

s/apple/ : The word to search for

/orange/ : The word to replace “apple” if found

3 : Replace each 3rd occurrence of “apple”

Replace the first nth occurrence of a word in a file

Now assume that you want to replace only the first nth occurrence of a word in a file, but you are not using the GNU version of sed (probably in a Mac computer) to do this enter the following in a terminal

$ tr '\n' '\0' < file.txt | sed 's/apple/orange/3' | tr '\0' '\n' 
apple apple orange apple 
apple apple apple apple

Wow, it's a bit more complicated, right? don't worry I will explain everything

  • tr '\n' '\0' : Replaced file.txt new line characters with null bytes, which are highly unlikely to exist in a normal text file, but if they occur will create wrong results
  • Then sed will treat the file like a single line of data and replace the 3rd occurrence of “apple” with “orange”
  • lastly tr '\0' '\n' will replace null bytes with the new-line character

If you are using the GNU sed, (probably on a Linux computer) is more straightforward and less error-prone

$ sed -z 's/apple/orange/3' file.txt 
apple apple orange apple 
apple apple apple apple
  • -z parameter instructs sed to read the file as a single line instead as line by line, this forces sed to replace the nth occurrence only once since treats it as a single line

Conclusion

In this article, we saw how we can use sed to replace nth occurrences of a file, this can be very useful in file clean-ups or other repetive tasks and you want to avoid using a scripting language such as Python.