使用 grep 和 sed 查找和替换字符串 [英] Using grep and sed to find and replace a string

查看:71
本文介绍了使用 grep 和 sed 查找和替换字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下内容递归搜索目录以查找特定字符串并将其替换为另一个:

I am using the following to search a directory recursively for specific string and replace it with another:

grep -rl oldstr path | xargs sed -i 's/oldstr/newstr/g'

这个没问题.唯一的问题是,如果字符串不存在,则 sed 会失败,因为它没有任何参数.这对我来说是个问题,因为我使用 ANT 自动运行它并且构建失败,因为 sed 失败.

This works okay. The only problem is that if the string doesn't exist then sed fails because it doesn't get any arguments. This is a problem for me since i'm running this automatically with ANT and the build fails since sed fails.

有没有办法让它在找不到字符串的情况下防故障?

Is there a way to make it fail-proof in case the string is not found?

我对我可以使用的单行简单解决方案感兴趣(不一定与 grepsed 一起使用,但必须使用像这样的常见 unix 命令).

I'm interested in a one line simple solution I can use (not necessarily with grep or sed but with common unix commands like these).

推荐答案

你可以使用 find-exec 直接进入 sed 而不是首先使用 grep 定位 oldstr.它可能效率稍低,但这可能并不重要.这样,对 find 列出的所有文件执行 sed 替换,但如果 oldstr 不存在,它显然不会对

You can use find and -exec directly into sed rather than first locating oldstr with grep. It's maybe a bit less efficient, but that might not be important. This way, the sed replacement is executed over all files listed by find, but if oldstr isn't there it obviously won't operate on it.

find /path -type f -exec sed -i 's/oldstr/newstr/g' {} ;

这篇关于使用 grep 和 sed 查找和替换字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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