当前位置 博文首页 > 完美解决mac环境使用sed修改文件出错的问题

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

    作者:admin 时间:2021-06-21 18:30

    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修改文件出错的问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持站长博客。

    js