mac环境使用sed修改文件出错的解决方法
2016-04-26 20:51
661 查看
sed是linux命令,用于处理文件内容(修改,替换等),mac中都可以使用,但发现相同的替换命令在linux可以正常执行,在mac则执行失败。
在linux执行正常,但在mac环境下执行出现以下错误:
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,则不备份。
例如执行
则会创建一个example.txt_bak的备份文件,文件内容为修改前的example.txt内容
执行结果
执行前会备份源文件到Config.php_bak
2.如果不需要备份,把update_config.sh修改为
执行结果
出错原因
用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);
相关文章推荐
- Linux socket 初步
- android wifi 无线调试
- Linux Kernel 4.0 RC5 发布!
- linux lsof详解
- linux 文件权限
- Linux 执行数学运算
- 10 篇对初学者和专家都有用的 Linux 命令教程
- Linux 与 Windows 对UNICODE 的处理方式
- Ubuntu12.04下QQ完美走起啊!走起啊!有木有啊!
- 解決Linux下Android开发真机调试设备不被识别问题
- 运维入门
- 运维提升
- Linux 自检和 SystemTap
- 动态清空 nohup 输出文件
- install scrapy with pip and easy_install
- Ubuntu Linux使用体验
- c语言实现hashmap(转载)