If you don't know the content of your AAA and BBB strings, you must avoid taking the risk of changing the sed separator (the classic /
) for another that could be in your strings. So it is better to escape in your string the well known character used as a separator (and why not the classic /
).
You can use parameter expansion ${i/p/r}
to escape the slashes.
In this case ${i//p/r}
for escaping all occurrences.
$p1=${p1//\//\\/}
$p2=${p2//\//\\/}
sed s/$p1/$p2/ file
Or, more concise, in one line sed s/${p1//\//\\/}/${p2//\//\\/}/ file
The string looks odd. The content of the expansion of ${p1//\//\\/}
is in four parts : //
, \/
, /
, \\/
- the two first pair of slashes
//
is a separator in parameter expansion saying we are matching all occurrences of the template,
- then
\/
is for escaping the slash character in the search template,
- the
/
is a second separator in the expansion,
- and then
\\/
is the replacement string, in witch the backslash must be escaped.