命令行:搜索和替换所有与 grep 匹配的文件名 [英] Command line: search and replace in all filenames matched by grep

查看:32
本文介绍了命令行:搜索和替换所有与 grep 匹配的文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在与 grep 匹配的所有文件中搜索和替换字符串:

I'm trying to search and replace a string in all files matched by grep:

grep -n 'foo' * 会给我以下形式的输出:

grep -n 'foo' * will give me output in the form:

[filename]:[line number]:[text]

对于 grep 返回的每个文件,我想通过将 foo 替换为 bar 来修改文件.

For each file returned by grep, I'd like to modify the file by replacing foo with bar.

推荐答案

你的意思是在所有与 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

这篇关于命令行:搜索和替换所有与 grep 匹配的文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆