How to grep and replace

后端 未结 9 1546
囚心锁ツ
囚心锁ツ 2020-11-27 08:47

I need to recursively search for a specified string within all files and subdirectories within a directory and replace this string with another string.

I know that t

相关标签:
9条回答
  • 2020-11-27 09:42

    Another option would be to just use perl with globstar.

    Enabling shopt -s globstar in your .bashrc (or wherever) allows the ** glob pattern to match all sub-directories and files recursively.

    Thus using perl -pXe 's/SEARCH/REPLACE/g' -i ** will recursively replace SEARCH with REPLACE.

    The -X flag tells perl to "disable all warnings" - which means that it won't complain about directories.

    The globstar also allows you to do things like sed -i 's/SEARCH/REPLACE/g' **/*.ext if you wanted to replace SEARCH with REPLACE in all child files with the extension .ext.

    0 讨论(0)
  • 2020-11-27 09:44

    I got the answer.

    grep -rl matchstring somedir/ | xargs sed -i 's/string1/string2/g'
    
    0 讨论(0)
  • 2020-11-27 09:44

    You could even do it like this:

    Example

    grep -rl 'windows' ./ | xargs sed -i 's/windows/linux/g'
    

    This will search for the string 'windows' in all files relative to the current directory and replace 'windows' with 'linux' for each occurrence of the string in each file.

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