Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I do a recursive find/replace of a string with awk or sed?

How do I find and replace every occurrence of:

subdomainA.example.com 

with

subdomainB.example.com 

in every text file under the /home/www/ directory tree recursively?

like image 432
Tedd Avatar asked Oct 17 '09 21:10

Tedd


People also ask

Is sed recursive?

Current directory and subdirectories, recursiveYou can supplement sed with find to expand your scope to all of the current folder's subdirectories. This will include any hidden files. This will exclude any file that has the string /.

How do you replace a word with awk in Unix?

awk has two functions; sub and gsub that we can use to perform substitutions. sub and gsub are mostly identical for the most part, but sub will only replace the first occurrence of a string. On the other hand, gsub will replace all occurrences.

Is used for search a string recursively in all directories?

You can use grep command or find command as follows to search all files for a string or words recursively.


1 Answers

find /home/www \( -type d -name .git -prune \) -o -type f -print0 | xargs -0 sed -i 's/subdomainA\.example\.com/subdomainB.example.com/g' 

-print0 tells find to print each of the results separated by a null character, rather than a new line. In the unlikely event that your directory has files with newlines in the names, this still lets xargs work on the correct filenames.

\( -type d -name .git -prune \) is an expression which completely skips over all directories named .git. You could easily expand it, if you use SVN or have other folders you want to preserve -- just match against more names. It's roughly equivalent to -not -path .git, but more efficient, because rather than checking every file in the directory, it skips it entirely. The -o after it is required because of how -prune actually works.

For more information, see man find.

like image 193
Nikita Fedyashev Avatar answered Oct 04 '22 14:10

Nikita Fedyashev