Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sed replace every nth occurrence

Tags:

replace

sed

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
like image 422
tim Avatar asked May 02 '11 14:05

tim


People also ask

How do you remove lines from a file in Unix?

To Remove the lines from the source file itself, use the -i option with sed command. If you dont wish to delete the lines from the original source file you can redirect the output of the sed command to another file.

Which one among the following is used to substitute only second occurance of a word?

sed + replace only the second match word.


1 Answers

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}
like image 140
brandizzi Avatar answered Oct 28 '22 10:10

brandizzi