Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find and replace all occurrences of a string recursively in a directory tree? [duplicate]

Using just grep and sed, how do I replace all occurrences of:

a.example.com 

with

b.example.com 

within a text file under the /home/user/ directory tree recursively finding and replacing all occurrences in all files in sub-directories as well.

like image 776
Tony Avatar asked Oct 18 '09 15:10

Tony


People also ask

How do you replace a string that occurs multiple times in multiple files inside a directory?

s/search/replace/g — this is the substitution command. The s stands for substitute (i.e. replace), the g instructs the command to replace all occurrences.

How do you replace all occurrences of a string in Linux?

Find and replace text within a file using sed command Use Stream EDitor (sed) as follows: sed -i 's/old-text/new-text/g' input.txt. The s is the substitute command of sed for find and replace. It tells sed to find all occurrences of 'old-text' and replace with 'new-text' in a file named input.txt.

How do I find a string recursively?

To recursively search for a pattern, invoke grep with the -r option (or --recursive ). When this option is used grep will search through all files in the specified directory, skipping the symlinks that are encountered recursively.


2 Answers

Try this:

find /home/user/ -type f | xargs sed -i  's/a\.example\.com/b.example.com/g' 

In case you want to ignore dot directories

find . \( ! -regex '.*/\..*' \) -type f | xargs sed -i 's/a\.example\.com/b.example.com/g' 

Edit: escaped dots in search expression

like image 54
vehomzzz Avatar answered Sep 21 '22 05:09

vehomzzz


Try this:

grep -rl 'SearchString' ./ | xargs sed -i 's/REPLACESTRING/WITHTHIS/g' 

grep -rl will recursively search for the SEARCHSTRING in the directories ./ and will replace the strings using sed.

Ex:

Replacing a name TOM with JERRY using search string as SWATKATS in directory CARTOONNETWORK

grep -rl 'SWATKATS' CARTOONNETWORK/ | xargs sed -i 's/TOM/JERRY/g' 

This will replace TOM with JERRY in all the files and subdirectories under CARTOONNETWORK wherever it finds the string SWATKATS.

like image 39
Abhinav Deshpande Avatar answered Sep 21 '22 05:09

Abhinav Deshpande