Perl 在linux中如何搜索字符串并用其他字符串替换它?
我想搜索Perl 在linux中如何搜索字符串并用其他字符串替换它?,perl,shell,replace,grep,Perl,Shell,Replace,Grep,我想搜索字符串,并在目录下递归地将其替换为另一个字符串。 例如: 我想搜索一个字符串 “var gaJsHost=(((“https:==document.location.protocol”)”https://ssl." : "http://www.”;“ 并将其替换为 var _gaq=_gaq | |[]_gaq.push([''设置帐户','UA-7044592-1'])_gaq.push([''u setDomainName',news4u.com'])_gaq.push([''u t
字符串
,并在目录下递归地将其替换为另一个字符串
。
例如:
我想搜索一个字符串
“var gaJsHost=(((“https:==document.location.protocol”)”https://ssl." : "http://www.”;“
并将其替换为
var _gaq=_gaq | |[]_gaq.push([''设置帐户','UA-7044592-1'])_gaq.push([''u setDomainName',news4u.com'])_gaq.push([''u trackPageview'])代码>
如何实现它?使用find
查找所有文件,使用xargs
运行sed
修改文件:
find dir -type f | xargs sed -i.bak 's#from#to#'
它将查找dir下的所有文件,并将from替换为to,备份扩展名为“.bak”的原始文件
注意:from是一个基本的正则表达式,因此您需要转义正在搜索的字符串中的任何BRE元字符。最好在单个文件上测试sed命令以使其正常工作:
sed 's#from#to#' file > test.out
这将替换文件,但不是修改文件,而是将输出写入test.out,以便您可以检查结果。我在下面尝试了这段代码(我只是为了测试而用“goo”替换)find/home/project/new4u/apps/frontend/modules/alerts/templates/testing-type f-exec-sed-I“s/var gaJsHost=(\”https:\“==document.location.protocol)\?\“https:\/\/ssl.\”:\“http:\/\/www.\”/goo/“{}”\;
它工作不正常。我已转义了所有分隔符,但仍然不起作用。请告诉我要做哪些更改。转义太多,?
不是BRE元字符。此外,如果使用“
引用,则不需要转义”
字符,如果使用s#from#to#
而不是s/from/to/
,则无需转义/
字符。非常感谢。我不再逃跑了?和“它成功了。你能帮我吗?”