比如說我要替換version.txt文件中的version=1.1 為version=1.2,比如test.txt文件內容如下:
version=1.1
此時我們會使用sed來替換,如果是涉及比較多的處理,我們會采用腳本實現,比如sed_shell.sh腳本內容如下:
#!/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
sed -i s/$old_version/$new_version/g version.txt #替換老版本號為新版本號
fi
linux環境下:執行sh sed_shell.sh "1.2" 命令就可以把verison.txt的老版本號換成新版本號。
但是mac上執行就會報錯“invalid command code C”,查看mac sed 發現如下:
說白了,就是需要一個中間文件來轉換下,比如我們上面的sed命令在mac上可以替換成sed -i n.tmp s/$old_version/$new_version/g version.txt ,其實執行這條的時候會生成一個version.txt_n.tmp文件,這個不需要的文件,執行后刪除即可。
我們可以采用uname命令來判斷當前系統是不是mac,如果"$(uname)" == "Darwin",就表明是mac/ios系統。
所以完整的同時兼容linux和mac/ios的腳本sed_shell.sh如下:
#!/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
sed -i n.tmp s/$old_version/$new_verison/g version.txt 會導致新增一個文件version.txtn.tmp 可以把n.tmp換成空,
即sed -i " " s/$old_version/$new_verison/g version.txt ,就不會有新增文件
另一種方法是在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