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

查看:473
本文介绍了命令行:搜索并替换所有与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天全站免登陆