averyrandomusername
averyrandomusername

Reputation: 15

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.

Upvotes: 0

Views: 214

Answers (2)

averyrandomusername
averyrandomusername

Reputation: 15

The Solution

This solution works on Solaris 5.11

Perl perl-pe 's{Hello}{++$n == 2 ? $& : "World"}ge\' script > tmp && mv tmp script

Note: This changes the permissions of the script file. You will likely need to update the permissions using the following command:

chmod 777 script

For more information on file permissions, have a look over the documentation

Upvotes: 0

James Brown
James Brown

Reputation: 37404

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.

Upvotes: 1

Related Questions