使用grep和sed来查找和替换字符串 [英] Using grep and sed to find and replace a string
问题描述
我使用以下方法递归搜索特定字符串的目录并将其替换为另一个目录:
grep -rl oldstr路径| xargs sed -i's / oldstr / newstr / g'
这可以正常工作。唯一的问题是,如果字符串不存在,那么 sed
会失败,因为它没有得到任何参数。这对我来说是个问题,因为我使用ANT自动运行它,并且由于 sed
失败,构建失败。
有没有一种方法可以在找不到字符串的情况下使其失效?
我对可以使用的一行简单解决方案感兴趣(不一定使用 grep
或 sed
,但使用常见的unix命令)。
-exec
用于 sed
,而不是先用 grep
定位 oldstr
。这可能有点低效,但这可能并不重要。这样,对 find
列出的所有文件执行 sed
替换,但是如果 oldstr 不存在它显然不会对它进行操作。
find / path -type f -exec sed -i's / oldstr / newstr / g'{} \;
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'
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?
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).
解决方案 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屋!