Tuesday, October 18, 2011

Search and Replace in all files within a directory recursively on Linux

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]

No comments:

Post a Comment