完美解決mac環(huán)境使用sed修改文件出錯的問題
sed是linux命令,用于處理文件內(nèi)容(修改,替換等),mac中都可以使用,但發(fā)現(xiàn)相同的替換命令在linux可以正常執(zhí)行,在mac則執(zhí)行失敗。
出錯原因
用shell寫了個更新Config/Config.php版本的腳本,代碼如下:
#!/bin/bash file='Config/Config.php' old_version='1.1.0' new_version='1.1.1' #替換配置文件版本 sed -i "s/$old_version/$new_version/g" "$file" exit 0
在linux執(zhí)行正常,但在mac環(huán)境下執(zhí)行出現(xiàn)以下錯誤: $ cat ./Config/Config.php // 版本 define('VERSION', 1.1.0); $ ./update_config.sh sed: 1: "Config/Config.php": invalid command code C
man sed 查看原因,找到 -i 參數(shù)的說明
-i extension Edit files in-place, saving backups with the specified extension. If a zero-length extension is given, no backup will be saved. It is not recommended to give a zero-length extension when in-place editing files, as you risk corruption or partial content in situations where disk space is exhausted, etc.
原來sed -i需要帶一個字符串作為備份源文件的文件名稱,如果這個字符串長度為0,則不備份。
例如執(zhí)行
sed -i "_bak" "s/a/b/g" "example.txt"
則會創(chuàng)建一個example.txt_bak的備份文件,文件內(nèi)容為修改前的example.txt內(nèi)容
實(shí)例
1、如果需要備份源文件,update_config.sh修改為
#!/bin/bash file='Config/Config.php' old_version='1.1.0' new_version='1.1.1' #替換配置文件版本 sed -i "_bak" "s/$old_version/$new_version/g" "$file" exit 0
執(zhí)行結(jié)果
$ cat ./Config/Config.php // 版本 define('VERSION', 1.1.0); $ ./update_config.sh $ cat ./Config/Config.php // 版本 define('VERSION', 1.1.1); $ cat ./Config/Config.php_bak // 版本 define('VERSION', 1.1.0);
執(zhí)行前會備份源文件到Config.php_bak
2、如果不需要備份,把update_config.sh修改為
#!/bin/bash file='Config/Config.php' old_version='1.1.0' new_version='1.1.1' #替換配置文件版本 sed -i "" "s/$old_version/$new_version/g" "$file" exit 0 執(zhí)行結(jié)果 $ cat ./Config/Config.php // 版本 define('VERSION', 1.1.0); $ ./update_config.sh $ cat ./Config/Config.php // 版本 define('VERSION', 1.1.1);
以上這篇完美解決mac環(huán)境使用sed修改文件出錯的問題就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Linux中SELinux、Shell簡介、touch命令的應(yīng)用小結(jié)
SELinux(Security-Enhanced Linux)是美國國家安全局(NSA)對于強(qiáng)制訪問控制的實(shí)現(xiàn),是Linux歷史上最杰出的新安全子系統(tǒng),這篇文章主要介紹了Linux中SELinux、Shell簡介、touch命令的應(yīng)用知識總結(jié),需要的朋友可以參考下2023-02-02linux定時任務(wù)crontab 實(shí)現(xiàn)每秒執(zhí)行一次的方法
linux crontab 命令,最小的執(zhí)行時間是一分鐘。這篇文章主要介紹了linux定時任務(wù)crontab 實(shí)現(xiàn)每秒執(zhí)行一次的方法,需要的朋友可以參考下2018-03-03windows下上傳shell腳本不能運(yùn)行的解決方法
windows下上傳shell腳本不能運(yùn)行—將dos模式修改為unix 文件格式 就可以順利解決,下文給大家?guī)砹嗽敿?xì)解決方法,一起看看吧2018-06-06