Sed:每隔一个换行符替换一次模式?

Mat*_*ler 11 sed replace

有没有办法告诉sed在每第二次出现时替换模式?或者至少每隔一行?(当然可以使用脚本,但我问自己是否sed可以做到)。

编辑

我发现

sed -e "s/pattern/replacement/g;n"
Run Code Online (Sandbox Code Playgroud)

但它取代了每一次出现,而不是第二次。

例子

输入文件:

I have a pattern in each line
Also the second line has the pattern
Another pattern here
And -- you guess it -- a pattern
Run Code Online (Sandbox Code Playgroud)

期望的输出:

I have a pattern in each line
Also the second line has the replacement
Another pattern here
And -- you guess it -- a replacement
Run Code Online (Sandbox Code Playgroud)

llu*_*lua 15

sed 's/pattern/replacement/2'
Run Code Online (Sandbox Code Playgroud)

将替换具有该模式的每一行上的第二次出现。


如果你有 GNU sed

sed '1~2N ; s/pattern/replacement/2'
Run Code Online (Sandbox Code Playgroud)

从第一行开始1,它后面的行将被添加到模式空间,N然后s命令将替换第二次出现的模式。然后sed将向下移动两行~2并重复。


cas*_*cas 6

/sf/ask/410074031/

该解决方案使用 awk 而不是 sed,而是“使用正确的工具来完成这项工作”。这可能是也可能不是可能在sed做,但是,即使是这样,这将是一个很多像AWK或Perl的工具更容易。