command to search/replace text in a directory
I'm a little embarassed to admit this, but I've never learned any *nix command which can search every file in some directory and replace some string with another string and then save the file. Can anyone recommend a command to do this that is likely to work on all linux distros? Ideally this search/replace function will support regex for search and then backreferences for replacing (i.e., you can refer to the found text with $1 or \1 or whatever).
I humbly offer this one command which I have used to replace a string in a single file. It replaces all occurrences of the string Code:
perl -p -i.bak -e 's/searchString/replaceString/gi' file-to-search.txt Any help would be much appreciated. |
I don't know perl, but sed is very similar:
Code:
sed -i s/searchstring/replacestring/g files-wildcard-allowed The only standout point here is I forget if wildcards work ... yep it does, just checked and validated. Now the latter part where you said "search your entire directory of files" Code:
find . -type f -name "*.txt" -exec sed -i s/searchstring/replacestring/g {} \; I personally LOVE that feature of find and use it nearly everyday. And you can use that perl command (provided it works correctly) in place. The form of the find is: Code:
find <base-directory> -type f -name <file-search-spec> -exec <command to execute on the found file(s)> {} \; |
Thank you SO MUCH for this helpful, detailed post.
I am familiar with find and have used it with ls -l and chmod and chown and so on. I like this. |
All times are GMT -5. The time now is 03:36 AM. |