您现在的位置是:网站首页> 编程资料编程资料
完美解决mac环境使用sed修改文件出错的问题_linux shell_
2023-05-26
428人已围观
简介 完美解决mac环境使用sed修改文件出错的问题_linux shell_
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修改文件出错的问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
相关内容
- shell 使用数组作为函数参数的方法(详解)_linux shell_
- linux 中open()函数详解及简单实例_linux shell_
- Linux 中C语言getcwd()函数的用法_linux shell_
- linux crontab 实现每秒执行的实例_linux shell_
- crontab每10秒执行一次的实现方法_linux shell_
- 基于shell的if和else详解_linux shell_
- Vim中列出TODO与FIXME等备注的方法_linux shell_
- Linux bash删除文件中含“指定内容”的行功能示例_linux shell_
- 使用ntpdate工具校正linux服务器时间(实现方法)_linux shell_
- linux 下实现sleep详解及简单实例_linux shell_
