Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using grep and sed to find and replace a string

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).

like image 744
Michael Avatar asked May 30 '11 16:05

Michael


People also ask

Can I use grep and sed together?

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.

How can I replace text after a specific word using sed?

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.


2 Answers

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' {} \;
like image 174
Michael Berkowski Avatar answered Oct 16 '22 22:10

Michael Berkowski


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.

like image 28
jm666 Avatar answered Oct 16 '22 22:10

jm666