【问题标题】:Append string before and after在前后附加字符串
【发布时间】:2020-12-16 08:29:35
【问题描述】:

如何使用 bash 或 sed 在比赛前后放置字符串?模式前后各有 4 个空格。

输入:

Irrelevant text
    line of code
Irrelevant text

输出

Irrelevant text
    {code}line of code{code}
Irrelevant text

我试过了

CONTENT=$(while read -r line;
do     line=${line//'    '/'    {code}'};
line=${line//\n/'{code}'};     
echo $line; done < testfile)

但它没有产生我想要的输出。

编辑:如果我什至想在模式之前附加不同的字符串和在模式之后附加不同的字符串,我该怎么做?

【问题讨论】:

    标签: string bash sed


    【解决方案1】:

    考虑对整个文件使用“sed”。

    sed -e 's/    \(.*\)$/    {code}\1{code}/'
    

    s 运算符将选择组 #1 中空格后的文本,然后将已包装的组 (\1) 替换为 {code}

    使用sed 比逐行使用 bash 效率要高得多。

    【讨论】:

    • 你能解释一下 (.*)$ 吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-17
    • 2016-06-14
    • 2014-07-07
    • 1970-01-01
    • 2011-05-15
    相关资源
    最近更新 更多