一直以来,对linux“抽象”的命令行有畏惧心理。故,文本的查找/替换还是愿意用可视化的工具。
今天以前,我“标准”在做法是在VIM中,用EasyGrep插件。(因vim中的:vim命令只能查找替换当前buffer,欲在文件夹中进行,要经过好几步,我没有学会)。但此插件执行过程比较慢,而且时不时会出错。故,下定决心,学一下命令行的方式。
成果
我尝试出来的完美解决方案:
grep -e 'this' -rl . | xargs sed -i '' 's/this/that/g'
以上命令作用:将当前文件夹下(含子文件夹 )所有文件中的"this"替换为"that" [mac版本:OS X Yosemite 10.10.4,bash中]。如果字符串中含有"/",可以考虑用 "|" 来替代 "/",以省去 "//"的写法
命令及参数:
grep
The grep utility searches any given input files, selecting lines that match one or more patterns.
- -e
Specify a pattern used during the search of the input: an input line is selected if it matches any of the specified patterns. - -r
Recursively search subdirectories listed. - -l
Only the names of files containing selected lines are written to standard output.
xargs
The xargs utility reads space, tab, newline and end-of-file delimited strings from the standard input and executes utility with the strings as arguments.
sed (stream editor)
The sed utility reads the specified files, or the standard input if no files are specified, modifying the input as specified by a list of commands.
- -i
Edit files in-place, saving backups with the specified extension.
一般实践步骤
查找字符串,替换,确认已替换。如下:
- grep -e 'this' -r .
- grep -e 'this' -rl . | xargs sed -i '' 's/this/that/g' (此步必需)
- grep -e 'that' -r .
感谢
- 我的同事michael_jia的文章:Linux常用命令。他的版本如下:
grep -e 'this' -rl . | xargs sed -i 's/this/that/g'
此方法在CentOS上奏效,但在mac上报错:
sed: 1: "some file name": invalid command code .
(差异仅在于 -i 之后的 '' )
-
stackoverflow
文中提到的使用find方法查找的方案,可以替换成功,但是有一个问题:对于不含所查字符串的文件,sed处理后会加一个空行参考,无必要的修改。不知如何避免。