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

后端 未结 30 1607
盖世英雄少女心
盖世英雄少女心 2020-11-22 06:39

How do I find and replace every occurrence of:

subdomainA.example.com

with

subdomainB.example.com

in eve

相关标签:
30条回答
  • 2020-11-22 07:29

    An one nice oneliner as an extra. Using git grep.

    git grep -lz 'subdomainA.example.com' | xargs -0 perl -i'' -pE "s/subdomainA.example.com/subdomainB.example.com/g"
    
    0 讨论(0)
  • 2020-11-22 07:29
    find /home/www/ -type f -exec perl -i.bak -pe 's/subdomainA\.example\.com/subdomainB.example.com/g' {} +
    

    find /home/www/ -type f will list all files in /home/www/ (and its subdirectories). The "-exec" flag tells find to run the following command on each file found.

    perl -i.bak -pe 's/subdomainA\.example\.com/subdomainB.example.com/g' {} +
    

    is the command run on the files (many at a time). The {} gets replaced by file names. The + at the end of the command tells find to build one command for many filenames.

    Per the find man page: "The command line is built in much the same way that xargs builds its command lines."

    Thus it's possible to achieve your goal (and handle filenames containing spaces) without using xargs -0, or -print0.

    0 讨论(0)
  • 2020-11-22 07:29
    #!/usr/local/bin/bash -x
    
    find * /home/www -type f | while read files
    do
    
    sedtest=$(sed -n '/^/,/$/p' "${files}" | sed -n '/subdomainA/p')
    
        if [ "${sedtest}" ]
        then
        sed s'/subdomainA/subdomainB/'g "${files}" > "${files}".tmp
        mv "${files}".tmp "${files}"
        fi
    
    done
    
    0 讨论(0)
  • 2020-11-22 07:29

    Using combination of grep and sed

    for pp in $(grep -Rl looking_for_string)
    do
        sed -i 's/looking_for_string/something_other/g' "${pp}"
    done
    
    0 讨论(0)
  • 2020-11-22 07:30

    If you wanted to use this without completely destroying your SVN repository, you can tell 'find' to ignore all hidden files by doing:

    find . \( ! -regex '.*/\..*' \) -type f -print0 | xargs -0 sed -i 's/subdomainA.example.com/subdomainB.example.com/g'
    
    0 讨论(0)
  • 2020-11-22 07:32

    grep -lr 'subdomainA.example.com' | while read file; do sed -i "s/subdomainA.example.com/subdomainB.example.com/g" "$file"; done

    I guess most people don't know that they can pipe something into a "while read file" and it avoids those nasty -print0 args, while presevering spaces in filenames.

    Further adding an echo before the sed allows you to see what files will change before actually doing it.

    0 讨论(0)
提交回复
热议问题