sed is a linux command used to process file content (modification, replacement, etc.), and can be used in mac, but it is found that the same replacement command can be executed normally in linux, but fails to execute in mac.
Error reason
I wrote a script to update the Config/Config.php version using the shell, the code is as follows:
#!/bin/bash
file='Config/Config.php'
old_version='1.1.0'
new_version='1.1.1'
#replace config file version
sed -i "s/$old_version/$new_version/g" "$file"
exit 0
The execution is normal in linux, but the following error occurs when executing in the mac environment:
$ cat ./Config/Config.php
// Version
define('VERSION', 1.1.0);
$ ./update_config.sh
sed: 1: "Config/Config.php": invalid command code C
man sed Check the reason and find the description of the -i parameter
-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,则不备份。
例如执行
sed -i "_bak" "s/a/b/g" "example.txt"
则会创建一个example.txt_bak的备份文件,文件内容为修改前的example.txt内容
实例
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
执行结果
$ 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);
执行前会备份源文件到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
执行结果
$ cat ./Config/Config.php
// 版本
define('VERSION', 1.1.0);
$ ./update_config.sh
$ cat ./Config/Config.php
// 版本
define('VERSION', 1.1.1);
以上这篇完美解决mac环境使用sed修改文件出错的问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。