[Solved] bash : run sed -i multiple times


Running sed -i on the same file multiple times is a horrible antipattern. Just do all the substitutions in the same sed script.

You need to escape many more metacharacters than you currently do. See Escape a string for a sed replace pattern for some details. Probably that’s the reason many of your substitutions don’t appear to work.

Just briefly, try this:

# Escape metacharacters from both files and paste them side by side
paste -d / <(sed -e 's/[]%\/$*.^[]/\\&/g' search) <(sed -e 's/[\/&]/\\&/g' replace) |
# Add necessary decorations to turn this into a valid sed script
sed 's%^%s/%;s%$%/g%' |
# Now pass the generated sed script to another sed instance
sed -f - -i *.txt

You can peel off stuff from the end of the pipeline to see what’s being done at each step. I encourage you to do that in order to understand how this works. But just briefly, we turn pat.tern and repl&acement into pat\.tern/repl\&acement and then add the sed command around it so we get s/pat\.tern/repl\&acement/g; then feed that to sed -i.

As always, if your sed does not like -f -, try -f /dev/stdin or, in the absolutely worst case, save the generated file to a temporary file (don’t forget to remove it when you are done).

13

solved bash : run sed -i multiple times