LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (https://www.linuxquestions.org/questions/linux-general-1/)
-   -   command to search/replace text in a directory (https://www.linuxquestions.org/questions/linux-general-1/command-to-search-replace-text-in-a-directory-4175551387/)

sneakyimp 08-21-2015 04:46 PM

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
As I am unfamiliar with perl, the syntax is greek to me so I typically just go dig it up from my notes and use it almost verbatim. I'm hoping to find a solution which will search an entire directory of files, ideally letting you specify filename patterns, which is similar to the patterns used with PHP's preg_replace or with the grep command. I'd also note that I'm often frustrated with grep because its pattern matching doesn't behave exactly the same way as preg_replace.

Any help would be much appreciated.

rtmistler 08-21-2015 05:02 PM

I don't know perl, but sed is very similar:
Code:

sed -i s/searchstring/replacestring/g files-wildcard-allowed
Note that sed by default will just output to stdout but with the -i option, it will edit the files in place. Recommend that you try a sub-set of files, like instead of *.txt, maybe a*.txt and put it to stdout first before you add the -i option.

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 {} \;
Find all *.txt files starting from the current directory ".", execute that sed command on each "found" file, that's what the {} designates. To terminate the -exec directive for the find, you need the \;

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)> {} \;

sneakyimp 08-21-2015 05:49 PM

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.