Salt
Salt

Reputation: 59

Using sed to replace the second instance of an entire line

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

Upvotes: 0

Views: 951

Answers (1)

Ed Morton
Ed Morton

Reputation: 204164

Your requirements aren't clear and your sample input/output isn't helping but given this input file:

$ cat file
# randomtext 9876
foo
randomtext 9999
bar
randomtext 3

To replace the 2nd occurrence of randomtext:

$ awk '{print (/randomtext/ && (++c==2) ? "randomtext 123" : $0)}' file
# randomtext 9876
foo
randomtext 123
bar
randomtext 3

To replace all uncommented occurrences of randomtext:

$ awk '{print (/^[^#]*randomtext/ ? "randomtext 123" : $0)}' file
# randomtext 9876
foo
randomtext 123
bar
randomtext 123

To replace the 1st uncommented occurrence of randomtext:

$ awk '{print (/^[^#]*randomtext/ && (++c==1) ? "randomtext 123" : $0)}' file
# randomtext 9876
foo
randomtext 123
bar
randomtext 3

Upvotes: 2

Related Questions