Recursive search and replace in text files on Mac and Linux

后端 未结 14 685
不思量自难忘°
不思量自难忘° 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:45

    OS X uses a mix of BSD and GNU tools, so best always check the documentation (although I had it that less didn't even conform to the OS X manpage):

    https://web.archive.org/web/20170808213955/https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man1/sed.1.html

    sed takes the argument after -i as the extension for backups. Provide an empty string (-i '') for no backups.

    The following should do:

    LC_ALL=C find . -type f -name '*.txt' -exec sed -i '' s/this/that/ {} +

    The -type f is just good practice; sed will complain if you give it a directory or so. -exec is preferred over xargs; you needn't bother with -print0 or anything. The {} + at the end means that find will append all results as arguments to one instance of the called command, instead of re-running it for each result. (One exception is when the maximal number of command-line arguments allowed by the OS is breached; in that case find will run more than one instance.)

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

    For the mac, a more similar approach would be this:

    find . -name '*.txt' -print0 | xargs -0 sed -i "" "s/form/forms/g"
    
    0 讨论(0)
  • 2020-12-02 04:47

    I used this format - but...I found I had to run it three or more times to get it to actually change every instance which I found extremely strange. Running it once would change some in each file but not all. Running exactly the same string two-four times would catch all instances.

    find . -type f -name '*.txt' -exec sed -i '' s/thistext/newtext/ {} +
    
    0 讨论(0)
  • 2020-12-02 04:47

    could just say $PWD instead of "."

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

    On Mac OSX 10.11.5 this works fine:

    grep -rli 'old-word' * | xargs -I@ sed -i '' 's/old-word/new-word/g' @
    
    0 讨论(0)
  • 2020-12-02 04:48

    If you are using a zsh terminal you're able to use wildcard magic:

    sed -i "" "s/search/high-replace/g" *.txt

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