Linux命令行全局搜索和替换 [英] Linux command line global search and replace
问题描述
我试图查找和替换由grep的Linux机器上匹配的所有文件的字符串。我有什么,我想要做的一些作品,但我不能确定如何最好地把它们串在一起。
I'm trying to search and replace a string in all files matched by grep on a linux machine. I've got some pieces of what I want to do, but I'm unsure how best to string them all together.
的grep -n'富'*
会给我输出形式:
[filename]:[line number]:[text]
有关通过的grep返回每个文件,我想取代富与酒吧,结果写回文件。有没有做到这一点的好办法?也许看中管道?
For each file returned by grep, I'd like replace "foo" with "bar" and write the result back to the file. Is there a good way to do that? Maybe a fancy pipeline?
推荐答案
你的意思是搜索和替换通过的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
这篇关于Linux命令行全局搜索和替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!