sed命令:如何搜索从单词开始的第二行出现?
我有这个文件 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您似乎指望
-z
标志将整个输入解释为一行,以便将2
标志添加到您的s 命令导致整个文件中的第二个匹配项被替换。问题在于相关计数超过了非重叠匹配项。您的模式锚定到行尾,您需要在多行模式下进行匹配,以便有可能出现两个不重叠的匹配:
也就是说,向
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 the2
flag to yours
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:That is, add an
m
flag to thes
command.