sed 替换每第 n 次出现 [英] Sed replace every nth occurrence

查看:60
本文介绍了sed 替换每第 n 次出现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 sed 来替换文件中每隔一次出现的 html 元素,以便我可以制作交替的颜色行.

I am trying to use sed to replace every other occurrence of an html element of a file so I can make alternating color rows.

这是我尝试过的,但不起作用.

Here is what I have tried and it doesn't work.

sed 's/<tr valign=top>/<tr valign=top bgcolor='#E0E0E0'>/2' untitled.html

推荐答案

我会用 awk 解决:

I'd solve it with awk:

awk '/<tr valign=top>/&&v++%2{sub(/<tr valign=top>/, "<tr valign=top bgcolor='#E0E0E0'>")}{print}' untitled.html 

首先,它验证该行是否包含

First, it verifies if the line contains <tr valign=top>

/<tr valign=top>/&&v++%2

以及 是否是一个奇怪的发现实例:

and whether the <tr valign=top> is an odd found instance:

v++%2

如果是,则替换该行中的

If so, it replaces the <tr valign=top> in the line

{sub(/<tr valign=top>/, "<tr valign=top bgcolor='#E0E0E0'>")}

由于要打印所有行,因此有一个块将始终执行(对于所有行)并打印当前行:

Since all lines are to be printed, there is a block that always will be executed (for all lines) and will print the current line:

{print}

这篇关于sed 替换每第 n 次出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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