前言:
實際工作中遇到一個問題:需要在某一個文件下,將所有包含aaa字符串全部替換為bbb字符串。之前處理這種方式是用vim打開各個文件,進行編輯并批量替換。這次想用一個更方便的方法來實現(xiàn),想到了sed命令。
實現(xiàn)用過過程中遇到了問題:
sed -i “s/aaa/111/g” test.txt
這條語句在linux平臺下可以正常運行。但是在mac下運行會報錯。
如下:
? practice sed -i "s/aaa/bbb/g" test.txt
sed: 1: "test.txt": undefined label 'est.txt'
查看sed命令:
man sed
............
-i extension
Edit files in-place, saving backups with the specified extension. If a zero-length extension is given, no backup will be saved. It is not recom-
mended to give a zero-length extension when in-place editing files, as you risk corruption or partial content in situations where disk space is
exhausted, etc.
從上面的解釋可得出,-i 需要并且必須帶一個字符串,用來備份源文件,并且這個字符串將會加在源文件名后面,構(gòu)成備份文件名。
所以在mac下正確使用方式是這樣的:
? practice sed -i "" "s/aaa/bbb/g" test.txt
? practice
另外,如果不想用-i參數(shù),那么用如下的方法也可以實現(xiàn)
? practice sed "s/bbb/aaa/g" test.txt > test2.txt
? practice mv test2.txt test.txt
? practice
sed -i 的問題解決了,接下來就是實現(xiàn)某個文件夾的批量替換,實現(xiàn)的代碼如下:
在當(dāng)前目錄下,將所有aaaModule都替換為bbbName
grep -rl 'aaaModule' ./ | xargs sed -i "" "s/aaaModule/bbbName/g"
-r 表示搜索子目錄
-l 表示輸出匹配的文件名