There are two challenges:
Using text stored in a variable or file that should be treated literally when used as the regex argument to sed
's s///
function presents the challenge of having to escape regex metacharacters in that text.
Additionally, since you're talking about a block of text that's stored in file findtext.txt
, I assume you're talking about a multi-line solution - whereas sed
is single line-oriented by default.
The following solution addresses both challenges:
# Read the multiline search string into a variable
# and quote it to ensure literal treatment when used as a regex.
sometextQuoted=$(sed -e 's/[^^]/[&]/g; s/\^/\\^/g; $!a\'$'\n''\\n' < 'findtext.txt' |
tr -d '\n')
# Now process the *.php files:
# Read each file *as a whole* before performing the string replacement.
sed ':a; $!{N;ba}; s/'"$sometextQuoted"'/replacetext/g' *.php
The solution is based on this answer of mine, wich explains the sed
command used to quote (escape) the search text (sometextQuoted=...
) in detail.
':a; $!{N;ba}
is a standard sed
idiom that reads an entire file at once.
Note how "$sometextQuoted"
is spliced into the otherwise single-quoted sed
script to avoid confusion over what the shell interprets up front vs. what sed
ends up seeing.
Note that if you also wanted to read the replacement text (replacetext
in your example) from a variable/file, a different form of quoting (escaping) would be required - again, see the linked answer.
Note: The 2nd sed
command requires GNU sed
, which I assume you're using (-i
without an argument doesn't work with BSD/OSX sed
); it is possible, but more complex, to make this work with BSD/OSX sed
.
Also, I've omitted -i
from the command so you can check the results first without replacing the original files.