sed命令:如何搜索从单词开始的第二行出现?

发布于 2025-01-14 03:19:39 字数 774 浏览 2 评论 0原文

我有这个文件 simple.yml

services:
  - name: first
    image: first_image
    versionId: 1.0.0_first_image_id
  - name: second
    image: second_image
    versionId: 2.0.1_second_image_id

我正在尝试将第二次出现的 versionId 替换为以下值:versionId: image_id_edited 以便文件看起来像这样:

services:
  - name: first
    image: first_image
    versionId: 1.0.0_first_image_id
  - name: second
    image: second_image
    versionId: image_id_edited

这里的值 2.0.1_second_image_id 经常更改,因此我无法进行静态搜索。目前,我有这个 sed 命令,但它不起作用:

sed -rz "s/versionId:\s*.*\$/versionId: image_id_edited/2" -i simple.yaml

我想要一个正则表达式来搜索第二个 versionId: ... 直到它到达结尾行!谢谢!

I have this file simple.yml:

services:
  - name: first
    image: first_image
    versionId: 1.0.0_first_image_id
  - name: second
    image: second_image
    versionId: 2.0.1_second_image_id

I'm trying to replace the second occurrence of versionId with this value: versionId: image_id_edited so that the file would look like this:

services:
  - name: first
    image: first_image
    versionId: 1.0.0_first_image_id
  - name: second
    image: second_image
    versionId: image_id_edited

The value 2.0.1_second_image_id here is changed often, so I cannot do a static search. Currently, I have this sed command but it's not working:

sed -rz "s/versionId:\s*.*\$/versionId: image_id_edited/2" -i simple.yaml

I'd like to have a regex to search for the second versionId: ... until it reaches the end of the line! Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

兮子 2025-01-21 03:19:39

您似乎指望 -z 标志将整个输入解释为一行,以便将 2 标志添加到您的 s 命令导致整个文件中的第二个匹配项被替换。问题在于相关计数超过了非重叠匹配项。您的模式锚定到行尾,您需要在多行模式下进行匹配,以便有可能出现两个不重叠的匹配:

sed -rz 's/versionId:\s*.*$/versionId: image_id_edited/m2' -i simple.yaml

也就是说,向 m 添加一个 m 标志code>s 命令。

You appear to be counting on the -z flag to cause the whole input to be interpreted as a single line, so that the 2 flag to your s command results in the second match in the whole file being substituted. The problem is that the relevant count is over non-overlapping matches. Your pattern being anchored to the end of the line, you need to match in multiline mode in order for there to be a possibility of two non-overlapping matches:

sed -rz 's/versionId:\s*.*$/versionId: image_id_edited/m2' -i simple.yaml

That is, add an m flag to the s command.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文