一. bad way: change delimiter
sed s/xxx/ "$PWD" /
sed s:xxx: "$PWD" :
sed s@xxx@ "$PWD" @
也许那并非最终答案。
you can not known what character will occur in $PWD
, /
:
或者 @
.
if delimiter char in $PWD, they will break the expression
好的方法是替换(转义)$PWD
中的特殊字符。
二. good way: escape delimiter
for example:
try to replace URL
as $url (has :
/
in content)
x.com:80/aa/bb/aa.js
在字符串 $tmp 中
<a href="URL">URL</a>
A. use /
as delimiter
在使用sed表达式之前,在变量中将斜杠/
转义为\/
。
## 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>
或者
B. use :
as delimiter (more readable than /
)
在使用sed表达式之前,在var中将:
转义为:
。
在var中将:
转义为:
(在sed表达式中使用之前)。
## 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>