2017-04-19 25 views
0

我想掃描所有文件並替換所有實例。然而,當$ my_var從命令行輸入通過bash:替換命令中帶有斜槓的壞標記

read -p ' Input React route ' my_var

閱讀並通過\/HomePage\/

它拋出:sed: 1: "s/<Route component={P ...": bad flag in substitute command: 'H'

全bash腳本:

read -p ' Input React route ' my_var 
find . -maxdepth 1 -type f | xargs sed -i '' -e "s/<Route component={P} path=\"p.html\" routeName=\"p\" \/>/<Route component={L} path=\"$my_var\" routeName=\"L\" \/>/g" 

是有一種方法可以輸入並讓腳本運行而不必輸入轉義字符串?

+0

向我們展示您的實際文件和要替換的模式,而不是您嘗試和失敗的方式 – Inian

回答

0

我相信你成了我稱之爲「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" /> 

$ 
0

read過程反斜槓在輸入逸出 - \/被變成/被存儲在$my_var之前。

您可以使用read -r來避免這種情況。

$ read my_var <<<'hello\/world'; echo "$my_var" 
hello/world 
$ read -r my_var <<<'hello\/world'; echo "$my_var" 
hello\/world 

如果你有在組件斜槓它可能是有用的,sed使用不同的分離器也是如此,例如

sed -e "s:path=\"p.html\":path=\"$my_var\":g" 

會工作,即使$my_var包含一個斜槓,只要它不包含現在正被用作分隔符的字符:。您可以方便地選擇其他角色。

0

嘗試改變分隔符:

read -p ' Input React route ' my_var 
my_var=$(echo ${my_var} | sed -e 's_#_\\#_g') 
find . -maxdepth 1 -type f | xargs sed -i '' \ 
     -e 's#<Route component={P} path="p.html" routeName="p" />#<Route component={L} path="$my_var" routeName="L" />#g' 

這裏的技巧是,你可以改變任何你想要的分隔符。我也從在shell中使用雙引號改爲使用單引號。我認爲現在讓事情變得更加可讀!

唯一的是你需要現在取消#字符,但是sed會爲你做的很好。