Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to solve this match and replace problem of only nth occurrence of a word in a file in perl

Tags:

regex

perl

Suppose I have a file which has these few lines

Hello abc
hii
how are you
Hello abc

If I want to replace the 2nd occurrence of abc by xyz, how can I do?

I want an output like

Hello abc
hii
how are you
Hello xyz

I tried doing perl -pi -e 's/abc/xyz/ if $. == 2' filename. It is not working for me. Can anyone help me with this?


2 Answers

perl -i -pe's/abc/ ++$count == 2 ? "xyz" : "abc" /eg' file

This works even if abc appears more than once per line.

like image 162
ikegami Avatar answered Jan 01 '26 15:01

ikegami


Count the number of time abc appears and subst if equal 2:

perl -i -pe'$found++ if /abc/; s/abc/xyz/ if $found ==2' filename
like image 40
Toto Avatar answered Jan 01 '26 15:01

Toto