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).
This collection of sed and grep use cases might help you better understand how these commands can be used in Linux. Tools like sed (stream editor) and grep (global regular expression print) are powerful ways to save time and make your work faster.
The following `sed` command shows the use of 'c' to replace everything after the match. Here, 'c' indicates the change. The command will search the word 'present' in the file and replace everything of the line with the text, 'This line is replaced' if the word exists in any line of the file.
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' {} \;
Your solution is ok. only try it in this way:
files=$(grep -rl oldstr path) && echo $files | xargs sed....
so execute the xargs
only when grep return 0
, e.g. when found the string in some files.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With