Ripgrep(rg)搜索与批量替换技巧
1) 基础搜索(带行号)
sh
rg -n "TODO" .只搜某类文件:
sh
rg -n "useEffect" --glob "*.ts" --glob "*.tsx"忽略目录:
sh
rg -n "password" --glob "!node_modules/**" .2) 输出匹配文件列表(方便批处理)
sh
rg -l "oldName" .3) 批量替换(推荐两段式:先 preview 再 apply)
3.1 先预览会改哪些行
sh
rg -n "oldName" .3.2 替换(macOS 用 gsed 或 perl)
Linux 常用(GNU sed):
sh
rg -l "oldName" . | xargs sed -i 's/oldName/newName/g'Perl(跨平台相对稳定):
sh
rg -l "oldName" . | xargs perl -pi -e 's/oldName/newName/g'建议先
git diff看改动再提交。
4) 正则搜索(常用)
sh
# 查找 import 里用了相对路径的
rg -n "from '\\./" docs5) 我自己的习惯
- 先
rg -n看命中是否准确 - 再用
rg -l | xargs ...批量替换 - 最后
rg -n oldName再搜一遍确保改干净