sed command with -i option failing on Mac, but works on Linux

前端 未结 12 2098
情歌与酒
情歌与酒 2020-11-22 05:04

I\'ve successfully used the following sed command to search/replace text in Linux:

sed -i \'s/old_link/new_link/g\' *

However,

12条回答
  •  独厮守ぢ
    2020-11-22 06:02

    I've created a function to handle sed difference between MacOS (tested on MacOS 10.12) and other OS:

    OS=`uname`
    # $(replace_in_file pattern file)
    function replace_in_file() {
        if [ "$OS" = 'Darwin' ]; then
            # for MacOS
            sed -i '' -e "$1" "$2"
        else
            # for Linux and Windows
            sed -i'' -e "$1" "$2"
        fi
    }
    

    Usage:

    $(replace_in_file 's,MASTER_HOST.*,MASTER_HOST='"$MASTER_IP"',' "./mysql/.env")
    

    Where:

    , is a delimeter

    's,MASTER_HOST.*,MASTER_HOST='"$MASTER_IP"',' is pattern

    "./mysql/.env" is path to file

提交回复
热议问题