Recursive search and replace in text files on Mac and Linux

后端 未结 14 683
不思量自难忘°
不思量自难忘° 2020-12-02 04:18

In the linux shell, the following command will recursively search and replace all instances of \'this\' with \'that\' (I don\'t have a Linux shell in front of me, but it sho

相关标签:
14条回答
  • 2020-12-02 04:27
    find . -type f | xargs sed -i '' 's/string1/string2/g'
    

    Refer here for more info.

    0 讨论(0)
  • 2020-12-02 04:32

    https://bitbucket.org/masonicboom/serp is a go utility (i.e. cross-platform), tested on OSX, that does recursive search-and-replace for text in files within a given directory, and confirms each replacement. It's new, so might be buggy.

    Usage looks like:

    $ ls test
    a  d  d2 z
    $ cat test/z
    hi
    $ ./serp --root test --search hi --replace bye --pattern "*"                         
    test/z: replace hi with bye? (y/[n]) y
    $ cat test/z
    bye
    
    0 讨论(0)
  • 2020-12-02 04:33

    None of the above work on OSX.

    Do the following:

    perl -pi -w -e 's/SEARCH_FOR/REPLACE_WITH/g;' *.txt
    
    0 讨论(0)
  • 2020-12-02 04:33

    The command on OSX should be exactly the same as it is Unix under the pretty UI.

    0 讨论(0)
  • 2020-12-02 04:38

    This is my workable one. on mac OS X 10.10.4

    grep -e 'this' -rl . | xargs sed -i '' 's/this/that/g'
    

    The above ones use find will change the files that do not contain the search text (add a new line at the file end), which is verbose.

    0 讨论(0)
  • 2020-12-02 04:44

    A version that works on both Linux and Mac OS X (by adding the -e switch to sed):

    export LC_CTYPE=C LANG=C
    find . -name '*.txt' -print0 | xargs -0 sed -i -e 's/this/that/g'
    
    0 讨论(0)
提交回复
热议问题