mac上sed -i 執行失敗報錯

好比說我要替換version.txt文件中的version=1.1 爲version=1.2,好比test.txt文件內容以下:linux

version=1.1ios

此時咱們會使用sed來替換,若是是涉及比較多的處理,咱們會採用腳本實現,好比sed_shell.sh腳本內容以下:shell

#!/bin/bashbash

if [ "x$1" == "x" ]; then
    echo please input new version && exit
else
    old_version=`cat version.txt |grep version |awk -F "=" '{print $2}'` #獲取老的版本號
    new_version=$1
    echo old_version=$old_version and new_version=$new_version
    sed -i s/$old_version/$new_version/g version.txt  #替換老版本號爲新版本號
fithis

linux環境下:執行sh sed_shell.sh "1.2" 命令就能夠把verison.txt的老版本號換成新版本號。spa

可是mac上執行就會報錯「invalid command code C」,查看mac sed 發現以下:code

說白了,就是須要一箇中間文件來轉換下,好比咱們上面的sed命令在mac上能夠替換成sed -i  n.tmp s/$old_version/$new_version/g version.txt  ,其實執行這條的時候會生成一個version.txt_n.tmp文件,這個不須要的文件,執行後刪除便可。blog

咱們能夠採用uname命令來判斷當前系統是否是mac,若是"$(uname)" == "Darwin",就代表是mac/ios系統。input

因此完整的同時兼容linux和mac/ios的腳本sed_shell.sh以下:it

#!/bin/bash

if [ "x$1" == "x" ]; then #沒有輸入參數,報錯退出
    echo please input new version && exit
else
    old_version=`cat version.txt |grep version |awk -F "=" '{print $2}'`
    new_version=$1
    echo old_version=$old_version and new_version=$new_version
    if [ "$(uname)" == "Darwin" ];then #ios/mac系統
        echo "this is Mac,use diff sed"
        sed -i n.tmp s/$old_version/$new_verison/g version.txt  #若是不備份,能夠只給空,即sed -i  " " s/$old_version/$new_verison/g version.txt ,可是不能省略
        rm *.tmp
    else
        sed -i s/$old_version/$new_version/g version.txt  #linux系統
    fi
fi

 

另外一種方法是在mac上安裝gun-sed:

export xsed=sed
if [ "$(uname)" == "Darwin" ];then #mac系統
    echo "alias sed to gsed for Mac, hint: brew install gnu-sed"
    export xsed=gsed
fi

#後面使用xsed代替sed執行替換動做,

xsed -i s/$old_version/$new_version/g version.txt

相關文章
相關標籤/搜索