Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do multiple, in place seds for one original pattern search?

I am new to shell scripting and am attempting to solve a problem.

Basically, I need to find instances of a REGEX pattern in a text file, do some sed editing on each result, and then output the result in place to the original text file without disturbing any other original text.

The mental block I'm facing is that a) I need to do multiple pattern replacements in order to accomplish the final transformed result, so it can't be fit into a single call to sed, and b) if I grep out the results with a REGEX pattern, it gives me only the results that match that pattern. Ok great, so I go ahead and edit those to transform them into the final desired output, but I want to write this change exactly in place where it was in the text file. You can't pipe grep to sed -i because it doesn't reference the original file anymore, just the result set. Am I thinking about this in the wrong way or is there some command I'm just not aware of?

like image 329
John Kaybern Avatar asked Dec 01 '25 02:12

John Kaybern


1 Answers

You can "grep" before applying commands with sed's facilities for addressing:

sed '/grep-like regex/ s/pattern to replace/replacement/' -i file

Where the "-i file" tells sed to edit "file" in place.

Multple commands can be given ans separated either through semicolons or through the command line with multiple "-e" options:

sed -e '/regex1/ s/pattern1/replacement/' -e '/regex2/ s/pattern2/replacement/'
sed '/regex1/ s/pattern1/replacement/; /regex2/ s/pattern2/replacement/'

If in the example above regex1 and regex2 are the same, you can also group the replacement commands into a single block, by using backets:

sed '/regex/ { s/pattern1/replacement/; s/pattern2/replacement/ }'

or for the sake of clarity:

sed '/regex/ {
        s/pattern1/replacement/
        s/pattern2/replacement/
    }'

You can also further filter the lines to apply the commands by nesting the /regexes/:

sed '/regex1/ {
        s/pattern1/replacement/
        /regex2/ s/pattern2/replacement/
    }'

So the second substitute command is executed only if regex1 and regex2 match.

like image 119
Janito Vaqueiro Ferreira Filho Avatar answered Dec 02 '25 17:12

Janito Vaqueiro Ferreira Filho



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!