【问题标题】:Sed Pattern Match then Append to LineSed 模式匹配然后追加到行
【发布时间】:2022-01-13 03:41:39
【问题描述】:

我在下面有一些行,我正在尝试将“检查”附加到以 Apples 开头的行。有人知道我如何在与 Apple 相同的行上获得“检查”,而不是新行并打印输出吗?我一个人什么也做不了。

谢谢

我有什么:

Grocery store bank and hardware store
Apples Bananas Milk

我想要什么:

Grocery store bank and hardware store
Apples Bananas Milk Check

我尝试了什么:

sed -i '/^Apples/a Check' file

我得到了什么:

Grocery store bank and hardware store
Apples Bananas Milk
Check

【问题讨论】:

    标签: sed append


    【解决方案1】:

    这可能对你有用(GNU sed):

    sed '/Apples/s/$/ check/' file
    

    如果一行包含Apples,则附加字符串 check。其中$ 表示作为行尾的锚点(请参阅here)。

    【讨论】:

      【解决方案2】:

      使用sed

      $ sed '/^Apples/s/.*/& Check/' input_file
      Grocery store bank and hardware store
      Apples Bananas Milk Check
      

      你可以匹配以Apples开头的行,返回&附加Check

      【讨论】:

        【解决方案3】:

        问题是你a追加了a命令的行,见this reference

        “a”命令在范围或模式之后追加一行。

        你想要的只是一个替代品。但是,您可能还想实施更多调整,以下是一些建议:

        sed -i 's/Apples/& Check/g' file           # Adds ' Check' after each 'Apples'
        sed -i 's/\<Apples\>/& Check/g' file       # Only adds ' Check' after 'Apples' as whole word
        sed -i -E 's/\<Apples(\s+Check)?\>/& Check/g' file # Adds ' Check' after removing existing ' Check'
        

        请注意,这些建议仅适用于 GNU sed\&lt; 和 `>in GNU sed patterns are word boundaries,\s+matches one or more whitespaces in GNUsedPOSIX ERE patterns, and -E` 启用 POSIX ERE 模式语法。

        online demo

        #!/bin/bash
        s='Grocery store bank and hardware store
        Apples Bananas Milk'
        sed 's/Apples/& Check/g' <<< "$s"
        sed 's/\<Apples\>/& Check/g' <<< "$s"
        sed -E 's/\<Apples(\s+Check)?\>/& Check/g' <<< "$s"
        

        每种情况下的输出是:

        Grocery store bank and hardware store
        Apples Check Bananas Milk
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2022-01-17
          • 2013-09-30
          • 1970-01-01
          • 2016-08-27
          • 1970-01-01
          • 1970-01-01
          • 2014-03-30
          相关资源
          最近更新 更多