我相信你成了我稱之爲「bash-quoting-hell」的受害者。
看起來您的轉義/
在它作爲參數傳遞給sed
之前已被吃掉。這些問題通常由例如加倍反斜槓。
以下爲我工作(在bash在Cygwin上):
$ read -p ' Input React route ' my_var
Input React route \\/HomePage\\/
$ echo "<Route component={P} path=\"p.html\" routeName=\"p\" />" \
> | sed -e "s/<Route component={P} path=\"p.html\" routeName=\"p\" \/>/<Route component={L} path=\"$my_var\" routeName=\"L\" \/>/g"
<Route component={L} path="/HomePage/" routeName="L" />
$
這是不是很方便或用戶友好的(即使你自己就是用戶)。因此,我會添加一個預處理步驟:
$ read -p ' Input React route ' my_var
Input React route /HomePage/
$ my_var=$(echo "$my_var" | sed -e 's/\//\\\//g')
$ echo "<Route component={P} path=\"p.html\" routeName=\"p\" />" \
> | sed -e "s/<Route component={P} path=\"p.html\" routeName=\"p\" \/>/<Route component={L} path=\"$my_var\" routeName=\"L\" \/>/g"
<Route component={L} path="/HomePage/" routeName="L" />
$
Btw。還有另外一個更簡單的解決方案:可以更改sed
s s
命令中的分隔符。 (I下面的示例中使用#
):
$ read -p ' Input React route ' my_var
Input React route /HomePage/
$ echo "<Route component={P} path=\"p.html\" routeName=\"p\" />" \
> | sed -e "s#<Route component={P} path=\"p.html\" routeName=\"p\" \/>#<Route component={L} path=\"$my_var\" routeName=\"L\" \/>#g"
<Route component={L} path="/HomePage/" routeName="L" />
$
向我們展示您的實際文件和要替換的模式,而不是您嘗試和失敗的方式 – Inian