regexpython-3.xawksedprogramming-pearls

Replace Nth String Match In File


So I've found many solutions to using sed s/regexFind/replacement/n to replace the nth occurence of a word in a line.

For example s/hello hello hello/world/2 > hello world hello

What I'm looking to do however is update the update the third match occurrence over a file.

Hello
Hello
Hello
Hello
Hello

Basically the expectation was that sed -i s/Hello/world/2 $filename would replace the file contents to be:

Hello
World
Hello
Hello
Hello

However this is not the case. Any suggestions?

I'm looking to not use a Python style read-every-line solution, because the file I looking to replace substrings in is not UTF-8.


Solution

  • Here is one in GNU awk:

    $ awk 'BEGIN{RS=/^$/;ORS=""}$0=gensub(/Hello/,"World",2)' file 
    Hello
    World
    Hello
    Hello
    Hello
    

    It treats the whole file as a single record and gensub replaces the second match.