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

后端 未结 30 1585
盖世英雄少女心
盖世英雄少女心 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:33

    just to avoid to change also

    • NearlysubdomainA.example.com
    • subdomainA.example.comp.other

    but still

    • subdomainA.example.com.IsIt.good

    (maybe not good in the idea behind domain root)

    find /home/www/ -type f -exec sed -i 's/\bsubdomainA\.example\.com\b/\1subdomainB.example.com\2/g' {} \;
    
    0 讨论(0)
  • 2020-11-22 07:35

    You can use awk to solve this as below,

    for file in `find /home/www -type f`
    do
       awk '{gsub(/subdomainA.example.com/,"subdomainB.example.com"); print $0;}' $file > ./tempFile && mv ./tempFile $file;
    done
    

    hope this will help you !!!

    0 讨论(0)
  • 2020-11-22 07:36

    Here's a version that should be more general than most; it doesn't require find (using du instead), for instance. It does require xargs, which are only found in some versions of Plan 9 (like 9front).

     du -a | awk -F' '  '{ print $2 }' | xargs sed -i -e 's/subdomainA\.example\.com/subdomainB.example.com/g'
    

    If you want to add filters like file extensions use grep:

     du -a | grep "\.scala$" | awk -F' '  '{ print $2 }' | xargs sed -i -e 's/subdomainA\.example\.com/subdomainB.example.com/g'
    
    0 讨论(0)
  • 2020-11-22 07:36

    For Qshell (qsh) on IBMi, not bash as tagged by OP.

    Limitations of qsh commands:

    • find does not have the -print0 option
    • xargs does not have -0 option
    • sed does not have -i option

    Thus the solution in qsh:

        PATH='your/path/here'
        SEARCH=\'subdomainA.example.com\'
        REPLACE=\'subdomainB.example.com\'
    
        for file in $( find ${PATH} -P -type f ); do
    
                TEMP_FILE=${file}.${RANDOM}.temp_file
    
                if [ ! -e ${TEMP_FILE} ]; then
                        touch -C 819 ${TEMP_FILE}
    
                        sed -e 's/'$SEARCH'/'$REPLACE'/g' \
                        < ${file} > ${TEMP_FILE}
    
                        mv ${TEMP_FILE} ${file}
                fi
        done
    

    Caveats:

    • Solution excludes error handling
    • Not Bash as tagged by OP
    0 讨论(0)
  • 2020-11-22 07:38

    A straight forward method if you need to exclude directories (--exclude-dir=..folder) and also might have file names with spaces (solved by using 0Byte for both grep -Z and xargs -0)

    grep -rlZ oldtext . --exclude-dir=.folder | xargs -0 sed -i 's/oldtext/newtext/g'
    
    0 讨论(0)
  • 2020-11-22 07:39

    Try this:

    sed -i 's/subdomainA/subdomainB/g' `grep -ril 'subdomainA' *`
    
    0 讨论(0)
提交回复
热议问题