Recursive search and replace in text files on Mac and Linux

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

    Whenever I type this command I always seem to hose it up, or forget a flag. I created a Gist on github based off of TaylanUB's answer that does a global find replace from the current directory. This is Mac OSX specific.

    https://gist.github.com/nateflink/9056302

    It's nice because now I just pop open a terminal then copy in:

    curl -s https://gist.github.com/nateflink/9056302/raw/findreplaceosx.sh | bash -s "find-a-url.com" "replace-a-url.com"

    You can get some weird byte sequence errors, so here is the full code:

    #!/bin/bash
    #By Nate Flink
    
    #Invoke on the terminal like this
    #curl -s https://gist.github.com/nateflink/9056302/raw/findreplaceosx.sh | bash -s "find-a-url.com" "replace-a-url.com"
    
    if [ -z "$1" ] || [ -z "$2" ]; then
      echo "Usage: ./$0 [find string] [replace string]"
      exit 1
    fi
    
    FIND=$1
    REPLACE=$2
    
    #needed for byte sequence error in ascii to utf conversion on OSX
    export LC_CTYPE=C;
    export LANG=C;
    
    #sed -i "" is needed by the osx version of sed (instead of sed -i)
    find . -type f -exec sed -i "" "s|${FIND}|${REPLACE}|g" {} +
    exit 0
    
    0 讨论(0)
  • 2020-12-02 04:52

    As an alternative solution, I'm using this one on Mac OSX 10.7.5

    grep -ilr 'old-word' * | xargs -I@ sed -i '' 's/old-word/new-word/g' @
    

    Credit goes to: Todd Cesere's answer

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