Assume a string that contains one or multiple occurrences of three different keywords (abbreviated as "kw"). I would like to replace kw2 with some other string, say "qux". Specifically, I would like to replace that occurrence of kw2 that is the first one that is preceded by kw1 somewhere in the string (i.e., kw1 not necessarily adjacent to kw2) and followed by kw3 (i.e., kw2 not necessarily adjacent to kw3).
Examples:
> echo "foo kw1 bar kw2 baz kw3 kw2 baz kw3" | sed ...
# Desired output: foo kw1 bar qux baz kw3 kw2 baz kw3
> echo "foo kw2 bar kw1 bar kw2 baz kw3" | sed ...
# Desired output: foo kw2 bar kw1 bar qux baz kw3
Hi M Gruenstaeudl,
Your specification is a little bit ambiguous. If all three keywords are found in order in an input line more than once (as in the line:
kw1 kw2 kw3 kw1 kw2 kw3
in durden tyler's sample input), do you just want kw2 to be replaced in the first set of 3 keywords on the line as in the output Aia's perl script and durden tyler's awk script produce:
kw1 qux kw3 kw1 kw2 kw3
or did you want the 1st occurrence of kw2 to be replaced in each set of 3 keywords: