【问题标题】:Replace string which include \t \n in shell script在 shell 脚本中替换包含 \t \n 的字符串
【发布时间】:2017-05-05 15:07:59
【问题描述】:

文件 foo.h 是:

do {                                                              \
        if (a == b) {                                      \
            c = 1;                                         \
        }                                                         \
    \
} while (0)

在此,对于最后 2 行,模式将是

"\t\\\n} 而 (0)"

我想用

替换这个模式

"\t} while (0)".

我试过了

sed -i -- 's/\t\\\n} while (0)/\t} while (0)/g' "foo.h"

。但我没有达到预期。 我希望最终的 foo.h 应该是这样的:

 do {                                                              \
        if (a == b) {                                      \
            c = 1;                                         \
        }                                                         \
} while (0)

我们不能一起替换 "\t\\\n" 吗?或任何其他实用程序?

【问题讨论】:

    标签: bash shell replace sed tr


    【解决方案1】:

    你可以使用这个 gnu-sed 命令:

    sed -i 'N;s/\t\\\n\(} while (0)\)/\1/' foo.h
    
    cat foo.h
    
    do {                                                              \
            if (a == b) {                                      \
                c = 1;                                         \
            }                                                         \
    } while (0)
    
    【解决方案2】:

    您的问题是,sed 会按行读取和替换。

    这可以按照here, by Zsolt Botykai的解释规避

    因此,工作命令是:

    sed -e ':a;N;$!ba;s/\t\\\n} while/} while/g' foo.h
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-24
      • 2017-12-03
      • 2020-07-23
      • 1970-01-01
      • 1970-01-01
      • 2016-09-03
      • 2013-11-30
      • 2019-08-24
      相关资源
      最近更新 更多