Grep and sed (replace string in patterned lines)

Grep and Sed (replace string in patterned lines)

Hi all,
I want to grep for "PATTERN" and only if "PATTERN" is in a line, this line shall be used as replacement input e.g. for SED.

I don't get it running in one line.

NOT RUNNING - just first idea... I don't know how to redirect grep output to be used by sed in file

grep "PATTERN" FILENAME | xargs sed 's/ to be changed/, YEHA! to be changed/' [?FILE?]

Input example:

Expected output example:

Thanks a lot!

You can just use sed....

sed '/PATTERN/s/ to be changed/, YEHA! to be changed/' FILENAME
1 Like

Sometimes you just can wonder why you didn't find it :slight_smile:

I now remember that it was possible to add a pattern in front of sed substitution.
I don't want to substitute again, if i was obviously done in steps before. So it should be like

1.) Find PATTERN
2.) Only if element is "to be changed" but NOT ", YEHA! to be changed"
2.1.) than substitute "to be chaned" to ", YEHA! to bechanged"
2.2.) else (do nothing)

Thanks a lot!

final outcome:

sed '/PATTERN/s/ to be changed/, YEHA! to be changed/' test > tmp_file && mv tmp_file test

---------- Post updated at 03:15 PM ---------- Previous update was at 02:58 PM ----------

can I add a rule checking if substitution was done?

Example:
Input:
blah PATTERN 987654321 blub to be changed

Output after first run or otherwise manipulated: FINE
blah PATTERN 987654321 blub , YEHA! to be changed

Now if I rerun or if this was changed from other sources: SHOULD NOT BE SUBSTITUTED
blah PATTERN 987654321 blub , YEHA! , YEHA! to be changed

Note:
", YEHA! " can be between PATTERN and "to be changed" and rule should substitute if it's not directly in front of "to be changed"