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?
perl -i -pe's/abc/ ++$count == 2 ? "xyz" : "abc" /eg' file
This works even if abc appears more than once per line.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With