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
findand-execdirectly intosedrather than first locatingoldstrwithgrep. It’s maybe a bit less efficient, but that might not be important. This way, thesedreplacement is executed over all files listed byfind, but ifoldstrisn’t there it obviously won’t operate on it.