加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

完美解决mac环境使用sed修改文件出错的问题

发布时间:2020-12-15 05:15:55 所属栏目:安全 来源:网络整理
导读:sed是linux命令,用于处理文件内容(修改,替换等),mac中都可以使用,但发现相同的替换命令在linux可以正常执行,在mac则执行失败。 出错原因 用shell写了个更新Config/Config.php版本的脚本,代码如下: #!/bin/bashfile='Config/Config.php'old_version=

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

以上这篇完美解决mac环境使用sed修改文件出错的问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持编程小技巧。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读