Kaycee Kaycee - 1 year ago 53
Linux Question

Using sed to replace the second instance of an entire line linux

I am writing a bash script and I want to find a certain string and replace the entire line but on the second occurrence.

For example:

# randomtext 9876
randomtext 9999

I want to replace the 2nd occurrence of "randomtext" with "randomtext 123". So the final output should be like this:

# randomtext 9876
randomtext 123

I found a solution online which is quite similar to what I want but I am unsure on how to use it.

sed -i "0,/^PATTERN/ s/^PATTERN=.*$/PATTERN=XY/" test.txt

123 123
Answer Source

Assuming one per line.

In sed(can probz be reduced significantly)

sed 'x;/1/{s/./2/;x;s/.*/randomtext 123/;x};/^$/{x;/randomtext/{x;s/^/1/;x};x};x' file

In awk

awk '{x+=/randomtext/}x==2{sub(/.*/,"randomtext 123")}1' file

In perl

perl -pe 's/.*/randomtext 123/ if ($x+=/randomtext/)==2' file