這裏不使用sed
以下(容易)解決方案。
while read -r string from to wanted
do
echo "in [$string] want replace [$from] to [$to] wanted result: [$wanted]"
final=$(echo "$string" | sed "s/$from/$to/")
[[ "$final" == "$wanted" ]] && echo OK || echo WRONG
echo
done <<EOF
=xxx= xxx === =====
=abc= abc /// =///=
=///= /// abc =abc=
EOF
什麼打印
in [=xxx=] want replace [xxx] to [===] wanted result: [=====]
OK
in [=abc=] want replace [abc] to [///] wanted result: [=///=]
sed: 1: "s/abc/////": bad flag in substitute command: '/'
WRONG
in [=///=] want replace [///] to [abc] wanted result: [=abc=]
sed: 1: "s/////abc/": bad flag in substitute command: '/'
WRONG
無法抗拒:從來沒有做到這一點!(含sed)。 :)
是否有一種直接的方法來逃避 中的分隔符字符變量使用bash?
沒有,因爲你從變量傳遞字符串,你不能輕易逃脫分隔符,因爲在"s/$from/$to/"
分離不僅可以在$to
一部分,但在$from
部分也出現。例如。當你在$from
部分逃離分隔符時,它根本不會進行替換,因爲不會找到$from
。
解決方案:使用其他東西作爲sed
1)使用純慶典。在上面的腳本,而不是sed
使用
final=${string//$from/$to}
2)如果bash的替換是不夠的,用的東西是什麼,你可以通過$from
和$to
作爲變量。
final=$(echo "$string" | perl_from="$from" perl_to="$to" perl -pe 's/$ENV{perl_from}/$ENV{perl_to}/')
final=$(echo "$string" | perl -spe 's/$f/$t/' -- -f="$from" -t="$to")