且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

命令行:搜索和替换所有与 grep 匹配的文件名

更新时间:2022-05-12 08:35:01

你的意思是在所有与 grep 匹配的文件中搜索并替换一个字符串吗?

Do you mean search and replace a string in all files matched by grep?

perl -p -i -e 's/oldstring/newstring/g' `grep -ril searchpattern *`

编辑

因为这似乎是一个相当受欢迎的问题,所以我想我会更新.

Since this seems to be a fairly popular question thought I'd update.

现在我主要使用 ack-grep 因为它对用户更友好.所以上面的命令是:

Nowadays I mostly use ack-grep as it's more user-friendly. So the above command would be:

perl -p -i -e 's/old/new/g' `ack -l searchpattern`

要处理文件名中的空格,您可以运行:

To handle whitespace in file names you can run:

ack --print0 -l searchpattern | xargs -0 perl -p -i -e 's/old/new/g'

您可以使用 ack-grep 做更多事情.假设您只想将搜索限制为 HTML 文件:

you can do more with ack-grep. Say you want to restrict the search to HTML files only:

ack --print0 --html -l searchpattern | xargs -0 perl -p -i -e 's/old/new/g'

如果空白不是问题,它会更短:

And if white space is not an issue it's even shorter:

perl -p -i -e 's/old/new/g' `ack -l --html searchpattern`
perl -p -i -e 's/old/new/g' `ack -f --html` # will match all html files