首 页最新软件下载排行文章资讯投稿发布下载专题
维维下载站
您的位置:首页编程开发网络编程编程其它 → mac下使用sed修改文件出错问题完美解决办法

mac下使用sed修改文件出错问题完美解决办法

来源:维维整理 发布时间:2017-4-6 19:48:38 人气:

今天要给大家分享的是mac下使用sed修改文件出错问题完美解决办法,sed是linux命令,用于处理文件内容(修改,替换等),在mac中都能够使用,不过发现相同的替换命令在linux能够正常执行,在mac则执行失败,下面来看看解决办法吧。

出错原因说明

用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执行正常,不过在mac环境下执行出现以下错误:
 
$ cat ./Config/Config.php
// 版本
define('VERSION', 1.1.0);
 
$ ./update_config.sh

sed: 1: "Config/Config.php": invalid command code C

man sed 查看原因,找到 -i 参数的说明

-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);

相关下载
栏目导航
本类热门阅览