Man…this was difficult.
I have a directory on my computer (I run linux for my desktop) that has a bunch of directories in it. I needed to change one string in each of the files to be something else.
I did this like 2 months ago but this time I had a really hard time finding the solution. I also remember that last time I tried like 6 different commands and none of them worked.
So, to search recursively through directories, looking in all the files for a particular string, and to replace that string with something else (on linux), this command should work:
find ./ -type f -exec sed -i ‘s/string1/string2/’ {} \;
Where string1 is the search string and string2 is the replace string.
Just for future reference
(also, it looks like my wordpress theme is stylizing those single quotes to look like something else. When I copied and pasted that onto the command line I got this error: sed: -e expression #1, char 1: unknown command: `
I fixed it by replacing those ` (backtick) characters with single quotes)
Note: Be sure to replace the ` (backtick) characters in all these commands with single quotes.
[tags]search and replace, linux search and replace, recursive search and replace, sed, xargs[/tags]
Replace backslash / by pipe | in the sed command, e.g.:
grep -rl matchstring somedir/ | xargs sed -i ‘s|string1|string2|g’
Working for strings containing backslash, for example: html, javascript, url etc.
I used grep to search through multiple files
grep -r “search string1”
This gives me a very long list of files in multiple directories the need to be changed.
I tried using
grep -rl matchstring somedir/ | xargs sed -i ’s/search string1/search string2/’
somedir = my directory, however No such file or directory was found also no input files are found.
I have 600 occurances of “search string 1” that need to be replaced with “search string 2”.
Do the Double quotes vary beween Linux and Unix?
Thanks dude. This was a big help.
Sed works only on one line and is good only for simple operations. If you need to replace complex code check this:
http://website-security.info/tools/find-and-repla…
find ./ -type f -exec sed -i ’s/string1/string2/g’ {} ;
worked great for me.. Thanks
phoneynk
the code included above creates error
find: missing argument to `-exec'
when run on Ubuntu 10.10
Stuart Jansen's comment about using xargs worked like a charm – thank you to both of you