How to 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?


Note : Do not run this command on a folder including a git repo - changes to .git could corrupt your git index.

find /home/www -type f -print0 | xargs -0 sed -i 's/subdomainA.example.com/subdomainB.example.com/g'

From man find :

-print0 (GNU find only) tells find to use the null character () instead of whitespace as the output delimiter between pathnames found. This is a safer option if you files can contain blanks or other special character. It is recommended to use the -print0 argument to find if you use -exec command or xargs (the -0 argument is needed in xargs.).


Note : Do not run this command on a folder including a git repo - changes to .git could corrupt your git index.

find /home/www/ -type f -exec 
    sed -i 's/subdomainA.example.com/subdomainB.example.com/g' {} +

Compared to other answers here, this is simpler than most and uses sed instead of perl, which is what the original question asked for.


All the tricks are almost the same, but I like this one:

find <mydir> -type f -exec sed -i 's/<string1>/<string2>/g' {} +
  • find <mydir> : look up in the directory.

  • -type f :

    File is of type: regular file

  • -exec command {} + :

    This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command. The command is executed in the starting directory.

  • 链接地址: http://www.djcxy.com/p/47128.html

    上一篇: sed和awk有什么区别?

    下一篇: 如何用awk或sed进行递归查找/替换字符串?