如何搜索一个字符串,并将其替换为其他字符串在Linux? [英] how to search for a string and replace it with other string in linux?

查看:147
本文介绍了如何搜索一个字符串,并将其替换为其他字符串在Linux?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为字符串进行搜索,并用另一个字符串替换 / code>递归地在一个目录下。
例如:
我想搜索一个字符串



var gaJsHost =((https:= = document.location.protocol)https:// ssl。:http:// www。);



替换它

var _gaq = _gaq || []; _ gaq.push(['_ setAccount','UA-7044592-1']); _ gaq.push(['_ setDomainName','news4u.com']); _ gaq.push(['_trackPageview']);



如何实现它?

解决方案

<使用 find 查找所有文件, xargs 运行 sed

  find dir -type f | xargs sed -i.bak的#从#到#'

可以找到 dir ,并用替换,备份扩展名为.bak的原始文件



NB from 是一个基本的正则表达式,所以您需要转义您正在搜索的字符串中的任何BRE元字符。在单个文件上测试sed命令以使其运行是个好主意:

  sed's#from#到#'档案> test.out 

这将替换文件,而不是修改 file 它会将输出写入 test.out ,以便检查结果。


I want to search for a string and replace it with another string recursively under a directory. for example: I want to search for a string

"var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");"

and replace it with

var _gaq = _gaq || [];_gaq.push(['_setAccount', 'UA-7044592-1']);_gaq.push(['_setDomainName', 'news4u.com']);_gaq.push(['_trackPageview']);

How to achieve it ?

解决方案

Use find to find all files, and xargs to run sed to modify them:

find dir -type f | xargs sed -i.bak 's#from#to#'

that will find all files under dir and replace from with to, backing up the original files with the extension ".bak"

N.B. from is a basic regular expression, so you will need to escape any BRE metacharacters in the string you are searching for. It would be a good idea to test the sed command on a single file to get it working:

sed 's#from#to#' file > test.out

That will do the replacements to file but instead of modifying file it will write the output to test.out so you can check the results.

这篇关于如何搜索一个字符串,并将其替换为其他字符串在Linux?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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