简体   繁体   English

Sed 在另一个特定模式匹配后替换一个模式?

[英]Sed replace on a pattern after another specific pattern match?

I have a file that has multiple similar patterns, each delimited by unique headers on preceding lines.我有一个文件,它有多个相似的模式,每个模式都由前几行的唯一标题分隔。

I would like to match/replace the pattern string only after header3 in this example:在此示例中,我只想在header3之后匹配/替换pattern字符串:

header1
a
b
pattern
c

header2
a
b
c
d
pattern

header3
a
pattern
b
c
d

In my actual file, there may be any number of header strings, and any number of lines in between.在我的实际文件中,可能有任意数量的 header 字符串,以及介于两者之间的任意数量的行。 So, the number of lines before or after the header3 match cannot be defined.因此,无法定义header3匹配之前或之后的行数。

(Additionally, this machine does not have the gnu sed binary available, so this is not an option that can be used.) (另外,这台机器没有可用的 gnu sed 二进制文件,所以这不是一个可以使用的选项。)

I found an answer to my own question using an address range:我使用地址范围找到了我自己问题的答案:

sed -i -r '/header3/,/pattern/ s|pattern|replacement|' filename

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM