How to find and replace all occurrences of a string recursively in a directory tree?

前端 未结 8 1580
野性不改
野性不改 2020-12-12 18:01

Using just grep and sed, how do I replace all occurrences of:

a.example.com

with

b.example.com

within a

相关标签:
8条回答
  • 2020-12-12 18:38

    I know this is a really old question, but...

    1. @vehomzzz's answer uses find and xargs when the questions says explicitly grep and sed only.

    2. @EmployedRussian and @BrooksMoses tried to say it was a dup of awk and sed, but it's not - again, the question explicitly says grep and sed only.

    So here is my solution, assuming you are using Bash as your shell:

    OLDIFS=$IFS
    IFS=$'\n'
    for f in `grep -rl a.example.com .` # Use -irl instead of -rl for case insensitive search
    do
        sed -i 's/a\.example\.com/b.example.com/g' $f # Use /gi instead of /g for case insensitive search
    done
    IFS=$OLDIFS
    

    If you are using a different shell, such as Unix SHell, let me know and I will try to find a syntax adjustment.

    P.S.: Here's a one-liner:

    OLDIFS=$IFS;IFS=$'\n';for f in `grep -rl a.example.com .`;do sed -i 's/a\.example\.com/b.example.com/g' $f;done;IFS=$OLDIFS
    

    Sources:

    • Bash: Iterating over lines in a variable

    • grep(1) - Linux man page

    • Official Grep Manual

    • sed(1) - Linux man page

    • Official sed Manual

    0 讨论(0)
  • 2020-12-12 18:44

    For me works the next command:

    find /path/to/dir -name "file.txt" | xargs sed -i 's/string_to_replace/new_string/g'
    

    if string contains slash 'path/to/dir' it can be replace with another character to separate, like '@' instead '/'.

    For example: 's@string/to/replace@new/string@g'

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