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?
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 /.
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.
You can use grep command or find command as follows to search all files for a string or words recursively.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With