2017-04-18 33 views
0

我想通過下面的腳本的bash:遞歸grep和替換字符串

VARIABLE_TO_INSERT=5 


egrep -lR '<Route component={P} path="p.html" routeName="p" />' . | tr '\n' '\0' | xargs -0 -n1 sed -i '' 's/<Route component={L} path="'$variable_to_insert'" routeName="L"\/>/g'` 

其中$variable_to_insert早在外殼定義的<Route component={L} path="'$variable_to_insert'" routeName="L"\/>替換字符串的所有出現像中的所有文件<Route component={P} path="p.html" routeName="p" />在當前目錄腳本

回答

1

您可以通過使用find簡化這一點:

find . -maxdepth 1 -type f | xargs sed -i "s/<Route component={P} path=\"p.html\" routeName=\"p\" \/>/<Route component={L} path=\"$VARIABLE_TO_INSERT\" routeName=\"L\" \/>/g" 
#           |              | |                 | 
#           +-------------------- replace this --------------------+ +---------------------------- with this ----------------------------+ 

的Shell變量只能得到取代在雙引號字符串,這就是爲什麼我們正在做sed -i "s/.../.../g"

並注意$VARIABLE_TO_INSERT的情況—變量名區分大小寫。

-maxdepth 1只抓住文件在當前目錄下,你可以刪除它做在當前目錄中的文件和所有子目錄遞歸搜索。)

0

使用$ VARIABLE_TO_INSERT而不是$ variable_to_insert,因爲shell變量區分大小寫。

此外,它看起來像你錯過了s /// g第三個正斜槓。