【问题标题】:add text at the end of specific line在特定行的末尾添加文本
【发布时间】:2022-06-11 18:20:25
【问题描述】:

我有一个这样的 yaml 文件:

spec:
  values:
    image: xxxx.dkr.ecr.eu-west-1.amazonaws.com/xxxx:mypr-ij4uhtuh3

我发现在包含单词image 的行末尾添加此文本: # {"$imagepolicy": "xxx:xxx-test-pr333" } 非常困难。

我尝试过使用 sed、awk 和 ruby,但我无法弄清楚,sed 尤其容易混淆所有这些特殊字符和空格。

最终结果应该是这样的:

spec:
  values:
    image: xxxx.dkr.ecr.eu-west-1.amazonaws.com/xxxx:mypr-ij4uhtuh3 # {"$imagepolicy": "xxx:xxx-test-pr333" }

感谢任何提示。

【问题讨论】:

    标签: awk text sed


    【解决方案1】:

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

    sed 's/^\s*image:.*/&  # {"$imagepolicy": "xxx:xxx-test-pr333" }/' file
    

    匹配一个以空格开头的行 image: 并附加 # {"$imagepolicy": "xxx:xxx-test-pr333" }/ 到它。

    【讨论】:

      【解决方案2】:

      这样就可以了:

      sed '/image/s/$/ # {"$imagepolicy": "xxx:xxx-test-pr333" }/' file.yaml
      

      地址/image/ 匹配包含单词image 的行。正则表达式 $ 匹配行尾,并将其替换为您要添加的字符串,以便追加到行。

      【讨论】:

        【解决方案3】:

        awk 单线解决方案 - 测试并确认在 mawk 1.3.4、gawk 5.1.1 和 macos nawk 上工作。

        无论"image" 在一行中出现多少次,OFS(现在设置为所需的填充文本)只会被附加一次。由于FS 是整行^$,行只能有NF 值0(零字节行)或1(其他所有),所以现有的空格和制表符都不会被扭曲.

        • 一个额外的好处是它的编写方式,它甚至可以用于 gawk-unicode 模式以安全地将文本附加到纯二进制文件中的“行”(添加 RT 检查对于不以\n 结尾的文件),如果有需要的话。

        输入

        spec:
          values:
            image: xxxx.dkr.ecr.eu-west-1.amazonaws.com/xxxx:mypr-ij4uhtuh3
         
        

        代码

        {m,n,g}awk 'NF+=/image/' FS='^$' OFS=' # {"$imagepolicy": "xxx:xxx-test-pr333" }'
        

        输出

        spec:
          values:
            image: xxxx.dkr.ecr.eu-west-1.amazonaws.com/xxxx:mypr-ij4uhtuh3 # {"$imagepolicy": "xxx:xxx-test-pr333" }
        

        【讨论】:

          【解决方案4】:

          我会利用 GNU AWK 来完成这个任务,让 file.txt 内容成为

          spec:
            values:
              image: xxxx.dkr.ecr.eu-west-1.amazonaws.com/xxxx:mypr-ij4uhtuh3
          

          然后

          awk '{print $0 (/image/?" # {\"$imagepolicy\": \"xxx:xxx-test-pr333\" }":"")}' file.txt
          

          给出输出

          spec:
            values:
              image: xxxx.dkr.ecr.eu-west-1.amazonaws.com/xxxx:mypr-ij4uhtuh3 # {"$imagepolicy": "xxx:xxx-test-pr333" }
          

          解释:我使用了所谓的三元运算符 (condition?valueiftrue:valueiffalse) 所以如果当前行包含/image/ I print 连接当前行 ($0) 和给定字符串,否则将当前行与空字符串 ("") 连接,即不变行。请注意,"(并且只有 ")需要转义(\),因为它们在 GNU AWK 中用于分隔字符串。

          (在 gawk 4.2.1 中测试)

          【讨论】:

            猜你喜欢
            • 2015-05-13
            • 2013-04-05
            • 1970-01-01
            • 2017-03-04
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多