如何在BASH中查找和替换比赛的每个偶数出现? [英] How to find and replace every even-numbered appearance of a match in BASH?

查看:83
本文介绍了如何在BASH中查找和替换比赛的每个偶数出现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用sed -i 's/AAA/ZZZ/g' filename将文件中每次出现的"AAA"替换为"ZZZ".我需要将"AAA"的所有偶数外观替换为"ZZZ",例如:

I am using sed -i 's/AAA/ZZZ/g' filename to replace every occurance of "AAA" with "ZZZ" in a file. I need to instead replace every even-numbered appearance of "AAA" with "ZZZ", e.g.:

This is a AAA sentence. AAA
This is another AAA sentence.
This is yet AAA another AAA sentence.
This is AAA stillAAA AAA yet AAA another AAA sentence.

这将变成:

This is a AAA sentence. ZZZ
This is another AAA sentence.
This is yet ZZZ another AAA sentence.
This is ZZZ stillAAA ZZZ yet AAA another ZZZ sentence.

如何替换比赛的每个偶数出现?

How to replace every even-numbered appearance of a match?

推荐答案

以下是简短的gnu awk版本

Here is a short gnu awk version

awk '{ORS=NR%2==0?"ZZZ":RS}1' RS="AAA" file
This is a AAA sentence. ZZZ
This is another AAA sentence.
This is yet ZZZ another AAA sentence.
This is ZZZ stillAAA ZZZ yet AAA another ZZZ sentence.

这篇关于如何在BASH中查找和替换比赛的每个偶数出现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆