我相信你成了我称之为“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