天天看點

Centos中查找并替換某個目錄下所有檔案中的某個字元

1.批量查找某個目下檔案的包含的内容

cd etc

grep -rn "查找的内容" ./

檔案内容比較多的話,執行完指令需要等一會。

2.批量替換某個目下所有包含的檔案的内容

還是以etc目錄為例

cd etc

sed -i "s/查找的内容/替換後的内容/g" `grep -rl "查找的内容" ./`

用sed指令可以批量替換多個檔案中的字元串。

sed -i "s/原字元串/新字元串/g" `grep 原字元串 -rl 所在目錄`

例如:我要把mahuinan替換為huinanma,

執行指令:

sed -i "s/mahuinan/huinanma/g" 'grep mahuinan -rl /www'

這是目前linux最簡單的批量替換字元串指令了!

具體格式如下:

sed -i "s/oldString/newString/g" `grep oldString -rl /path`

執行個體代碼:

sed -i "s/大小多少/日月水火/g" `grep 大小多少 -rl /usr/aa`

sed -i "s/大小多少/日月水火/g" `grep 大小多少 -rl ./`

注意轉義:

執行個體:

sed -i "s/<script src=\"http:\/\/ajax.googleapis.com\/ajax\/libs\/jquery\/1.4\/query.min.js\" type=\"text\/javascript\"><\/script>/ /g" `grep '<script src="http:\/\/ajax.googleapis.com\/ajax\/libs\/jquery\/1.4\/jquery.min.js" type="text\/javascript"><\/script>' -rl test/`

sed -i "s/https:\/\/code.jquery.com\/jquery-1.12.4.min.js/<%=basePath%>\/js\/jquery\/jquery-1.12.4.min.js/g" `grep -rl "https:\/\/code.jquery.com\/jquery-1.12.4.min.js" ./`