一. bad way: change delimiter
sed 's/xxx/'"$PWD"'/'
sed 's:xxx:'"$PWD"':'
sed 's@xxx@'"$PWD"'@'
maybe those not the final answer,
you can not known what character will occur in $PWD
, /
:
OR @
.
if delimiter char in $PWD, they will break the expression
the good way is replace(escape) the special character in $PWD
.
二. good way: escape delimiter
for example:
try to replace URL
as $url (has :
/
in content)
x.com:80/aa/bb/aa.js
in string $tmp
<a href="URL">URL</a>
A. use /
as delimiter
escape /
as \/
in var (before use in sed expression)
## step 1: try escape
echo ${url//\//\\/}
x.com:80\/aa\/bb\/aa.js #escape fine
echo ${url//\//\/}
x.com:80/aa/bb/aa.js #escape not success
echo "${url//\//\/}"
x.com:80\/aa\/bb\/aa.js #escape fine, notice `"`
## step 2: do sed
echo $tmp | sed "s/URL/${url//\//\\/}/"
<a href="x.com:80/aa/bb/aa.js">URL</a>
echo $tmp | sed "s/URL/${url//\//\/}/"
<a href="x.com:80/aa/bb/aa.js">URL</a>
OR
B. use :
as delimiter (more readable than /
)
escape :
as \:
in var (before use in sed expression)
## step 1: try escape
echo ${url//:/\:}
x.com:80/aa/bb/aa.js #escape not success
echo "${url//:/\:}"
x.com\:80/aa/bb/aa.js #escape fine, notice `"`
## step 2: do sed
echo $tmp | sed "s:URL:${url//:/\:}:g"
<a href="x.com:80/aa/bb/aa.js">x.com:80/aa/bb/aa.js</a>
set -x
in the shell to get the shell to echo each command just before it executes them. This can clear up a lot of confusion. (Also, I often useset -u
to make de-referencing unset variables a hard error. (Seeset -e
too.)) – Carolynncarolynne