如何从命令行进行递归查找和替换?

How to do a recursive find and replace from the command line?

是否有一种简单的方法可以递归搜索目录层次结构中的所有文件以查找术语(例如 port)并将所有出现的该术语替换为另一个术语(例如 port-lookup)。

我试过this post中的建议,但它们只适用于单个文件。

试试这个

find ./ -type f -exec sed -i -e 's/port/port-lookup/g' {} \;

如果不想更改文件修改时间

grep -rl 'port' /search_in_this_dir | xargs sed -i 's/port/port-offset/g' 

如果您有最新版本的 bash (>4)

shopt -s globstar
sed -i 's/port/port-lookup/g' **/*

实现此目的的最简单(并且可以说是最纯粹和直观的)方法是执行递归文件 grep,然后将这些文件结果通过管道传输到 sed(通过 xargs)以处理 in-位置替换。

grep -r -l "port" | xargs -r -d'\n' sed -i 's/port/port-lookup/g'

There is a comprehensive community wiki answer on this topic that I would recommend reading over on the Unix & Linux exchange.

只有 1 个命令行:msr -rp dir1,dir2,file1,fileN -x port -o port-lookup -R

以上命令对文件portport-lookup中的纯文本进行递归搜索和替换。

  • 如果您想预览替换结果,请删除-R
  • 如果要预览和汇总文件列表和count/distribution,请添加-l
  • 如果要备份更改的文件,请添加 -K,如 -K -R-RK
  • 忽略大小写添加 -i-i -x-ix.
  • 如果要使用 C++/C#/Java/Scala Regex 语法,请使用 -t 而不是 -x.
  • 过滤文件名,如:包括 -f "\.(xml|java|cpp)$" ,排除 --nf "\.(so|a|lib|dll|obj)$"
  • 过滤目录名称,如:包括 -d "src" ,排除 --nd "^(target|\.git)$"
  • 过滤文件大小范围如:--s1 1/--s1 1B with/or --s2 1.20MB
  • 过滤文件上次写入时间范围如:--w1 2017-08-01 with/or --w2 "2017-08-12 11:20:30"

更多关于查找和替换文件或管道的用法见我打开的项目https://github.com/qualiu/msr (msr.exe / msr.gcc* / msr.cygwin are in the tools directory). Built-in usage and exmaples just run the exe. Docs like performance comparision with findstr and grep .