前言:
实际工做中遇到一个问题:须要在某一个文件下,将全部包含aaa字符串所有替换为bbb字符串。以前处理这种方式是用vim打开各个文件,进行编辑并批量替换。此次想用一个更方便的方法来实现,想到了sed命令。linux
实现用过过程当中遇到了问题:vim
sed -i “s/aaa/111/g” test.txt
这条语句在linux平台下能够正常运行。可是在mac下运行会报错。
以下:spa
➜ practice sed -i "s/aaa/bbb/g" test.txt sed: 1: "test.txt": undefined label 'est.txt'
查看sed命令:code
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 须要而且必须带一个字符串,用来备份源文件,而且这个字符串将会加在源文件名后面,构成备份文件名。
因此在mac下正确使用方式是这样的:ci
➜ practice sed -i "" "s/aaa/bbb/g" test.txt ➜ practice
另外,若是不想用-i参数,那么用以下的方法也能够实现字符串
➜ practice sed "s/bbb/aaa/g" test.txt > test2.txt ➜ practice mv test2.txt test.txt ➜ practice
sed -i 的问题解决了,接下来就是实现某个文件夹的批量替换,实现的代码以下:it
在当前目录下,将全部aaaModule都替换为bbbName grep -rl 'aaaModule' ./ | xargs sed -i "" "s/aaaModule/bbbName/g" -r 表示搜索子目录 -l 表示输出匹配的文件名