sed是linux命令,用于處理文件內(nèi)容(修改,替換等),mac中都可以使用,但發(fā)現(xiàn)相同的替換命令在linux可以正常執(zhí)行,在mac則執(zhí)行失敗。
出錯(cuò)原因
用shell寫了個(gè)更新Config/Config.php版本的腳本,代碼如下:
#!/bin/bashfile='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)以下錯(cuò)誤:$ cat ./Config/Config.php// 版本define('VERSION', 1.1.0);$ ./update_config.sh sed: 1: "Config/Config.php": invalid command code Cman sed 查看原因,找到 -i 參數(shù)的說(shuō)明
-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.
原來(lái)sed -i需要帶一個(gè)字符串作為備份源文件的文件名稱,如果這個(gè)字符串長(zhǎng)度為0,則不備份。
例如執(zhí)行
sed -i "_bak" "s/a/b/g" "example.txt"
則會(huì)創(chuàng)建一個(gè)example.txt_bak的備份文件,文件內(nèi)容為修改前的example.txt內(nèi)容
實(shí)例
1、如果需要備份源文件,update_config.sh修改為
#!/bin/bashfile='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í)行前會(huì)備份源文件到Config.php_bak
2、如果不需要備份,把update_config.sh修改為
#!/bin/bashfile='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修改文件出錯(cuò)的問(wèn)題就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選