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

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

    A bit old school but this worked on OS X.

    There are few trickeries:

    • Will only edit files with extension .sls under the current directory

    . must be escaped to ensure sed does not evaluate them as "any character"

    , is used as the sed delimiter instead of the usual /

    Also note this is to edit a Jinja template to pass a variable in the path of an import (but this is off topic).

    First, verify your sed command does what you want (this will only print the changes to stdout, it will not change the files):

    for file in $(find . -name *.sls -type f); do echo -e "\n$file: "; sed 's,foo\.bar,foo/bar/\"+baz+\"/,g' $file; done
    

    Edit the sed command as needed, once you are ready to make changes:

    for file in $(find . -name *.sls -type f); do echo -e "\n$file: "; sed -i '' 's,foo\.bar,foo/bar/\"+baz+\"/,g' $file; done
    

    Note the -i '' in the sed command, I did not want to create a backup of the original files (as explained in In-place edits with sed on OS X or in Robert Lujo's comment in this page).

    Happy seding folks!

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

    I just use tops:

    find . -name '*.[c|cc|cp|cpp|m|mm|h]' -print0 |  xargs -0 tops -verbose  replace "verify_noerr(<b args>)" with "__Verify_noErr(<args>)" \
    replace "check(<b args>)" with "__Check(<args>)" 
    
    0 讨论(0)
  • 2020-11-22 07:39
    perl -p -i -e 's/oldthing/new_thingy/g' `grep -ril oldthing *`
    
    0 讨论(0)
  • 2020-11-22 07:40

    For me the easiest solution to remember is https://stackoverflow.com/a/2113224/565525, i.e.:

    sed -i '' -e 's/subdomainA/subdomainB/g' $(find /home/www/ -type f)
    

    NOTE: -i '' solves OSX problem sed: 1: "...": invalid command code .

    NOTE: If there are too many files to process you'll get Argument list too long. The workaround - use find -exec or xargs solution described above.

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

    According to this blog post:

    find . -type f | xargs perl -pi -e 's/oldtext/newtext/g;'
    
    0 讨论(0)
  • 2020-11-22 07:42

    or use the blazing fast GNU Parallel:

    grep -rl oldtext . | parallel sed -i 's/oldtext/newtext/g' {}
    
    0 讨论(0)
提交回复
热议问题