sed 替换每第 n 次出现 [英] Sed replace every nth occurrence
问题描述
我正在尝试使用 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 以及 and whether the 如果是,则替换该行中的 If so, it replaces the 由于要打印所有行,因此有一个块将始终执行(对于所有行)并打印当前行: 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: 这篇关于sed 替换每第 n 次出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
<tr valign=top>
/<tr valign=top>/&&v++%2
是否是一个奇怪的发现实例:
<tr valign=top>
is an odd found instance:v++%2
<tr valign=top>
in the line{sub(/<tr valign=top>/, "<tr valign=top bgcolor='#E0E0E0'>")}
{print}
登录
关闭