偶尔的替换用 VSCode 或 JetBrains IDE 的类似 Cmd + Shift + H 的文件替换就可以了。
经常或快捷的使用,可以用 grep + sed 命令进行替换。
搜索试了几个命令,发现有空格的路径会导致一些错误。
一顿搜索,找到了一个解决办法,参考 Grep word within a file then copy the file:
--null告诉grep以 NUL 字符分割文件名-0告诉sed以 NUL 分割输入
最终命令示例,以 bar 替换 foo。
区分大小写:
$ grep -lr --null 'foo' * | xargs -0 sed -i '' 's/foo/bar/g'
不区分大小写:
$ grep -ilr --null 'foo' * | xargs -0 sed -i '' 's/foo/bar/gI'
grep-i, --ignore-case查找文件时不区分大小写-l, --files-with-matches返回文件名-R, -r, --recursive递归搜索子目录
sed-i默认sed会打印到标准输出,使用-i将直接在文件内编辑替换s替换g全局替换标志I大小写不敏感标志
示例。
替换需求:
- 
+ 
可能有需要转义的:
查找的字符串、替换的内容:
](/img
](https://example.com/img
转义后:
](\/img
https:\/\/example.com\/img
将转义后的内容代入就可以了,完整的:
$ grep -lr --null '](\/img' | xargs -0 sed -i '' 's/](\/img/](https:\/\/example.com\/img/g'