与SED匹配后如何替换2条线
在使用SED发现比赛后,有没有办法替换以下两条线?
我有一个文件
#ABC
oneSize=bar
twoSize=bar
threeSize=foo
,但是一旦模式#abc
匹配,我想替换两个即时
#ABC
oneSize=foo
twoSize=foo
threeSize=foo
行 gsed'/^#abc/{n; s/size = bar/size = foo/}'文件
,
但它仅更改行twosize
not not oneyize < /code>
是否有一种方法可以使其更改OneSize和Twosize
Is there a way to replace the following two lines after a match is found using sed?
I have a file
#ABC
oneSize=bar
twoSize=bar
threeSize=foo
But I would like to replace the two immediate lines once the pattern #ABC
is matched so that it becomes
#ABC
oneSize=foo
twoSize=foo
threeSize=foo
I'm able to dogsed '/^#ABC/{n;s/Size=bar/Size=foo/}' file
But it only changes the line twoSize
not oneSize
Is there a way to get it to change both oneSize and twoSize
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以重复这些命令:
请参阅在线演示。
n
命令 "打印模式空间,然后无论如何,用下一行输入替换模式空间。如果没有更多输入,则 sed 退出而不处理任何其他命令。”因此,第一次使用它时,您将替换它。在以以下开头的行之后的第一行
#ABC
,然后替换该行下面的第二行。You can repeat the commands:
See the online demo.
The
n
command "prints the pattern space, then, regardless, replace the pattern space with the next line of input. If there is no more input then sed exits without processing any more commands."So, the first time it is used, you replace on the first line after line starting with
#ABC
, then you replace on the second line below that one.GNU和其他一些SED版本允许您使用相对号码抓住范围,因此您可以简单地使用:
命令详细信息:
/^#ABC $/,+2
匹配范围来自模式#ABC
到下一个2行s/(size =)bar/\ 1foo/
:matchsize = size = bar
并用替换size = foo
,使用捕获组避免在搜索和替换中重复同一字符串,您也可以考虑
awk
,以避免重复模式和替换n次,如果您必须在之后替换n行匹配模式:gnu and some other sed versions allow you to grab a range using relative number so you can simply use:
Command details:
/^#ABC$/,+2
Match range from pattern#ABC
to next 2 liness/(Size=)bar/\1foo/
: MatchSize=bar
and replace withSize=foo
, using a capture group to avoid repeat of same String in search and substitutionYou may also consider
awk
to avoid repeating pattern and replacements N times if you have to replace N lines after matching pattern:使用
sed
,当不再找到Size=bar
时,循环将中断,因此替换匹配后的前两行。Using
sed
, the loop will break whenSize=bar
is no longer found therefore replacing the first 2 lines after the match.使用sed -z
或
Using sed -z
Or