max max - 3 years ago 119
Bash Question

how to replace character in html attribute value (shell / bash)?

Sorry for the stupid question, but I have been stuck all afternoon with this simple problem. So I have a sample text file containing:

<product productId="123456" description="good apple, very green" publicPriceTTC="5,07" brand-id="152" />
<product productId="123457" description="fresh orange, very juicy" publicPriceTTC="12,47" brand-id="153" />
<product productId="123458" description="big banana, very yellow" publicPriceTTC="5,07" brand-id="154" />


And I'd like to modify this file into:

<product productId="123456" description="good apple, very green" publicPriceTTC="5.07" brand-id="152" />
<product productId="123457" description="fresh orange, very juicy" publicPriceTTC="12.47" brand-id="153" />
<product productId="123458" description="big banana, very yellow" publicPriceTTC="5.07" brand-id="154" />


Basically, I need to replace the "," (comma) by a "." (point) in all values of "publicPriceTTC". The trick here is that other attributes might have commas in their values ("description" in this example). I guess sed or awk can do that but I was unable to achieve it.

Can someone help me? Thank you very much for any help.

Answer Source

If you search for a comma to replace with a point, you will be doing a very coarse search/replace. Try something more especific. With sed, assume your input file is called xml:

sed -E 's/(publicPriceTTC="[0-9]+),([0-9]+")/\1.\2/' xml

You probably know that sed has the command s/<what you search>/<replacement>. We use that.

The -E option triggers the use of extended regular expressions. With that the s expression matches the whole tag + "=" + number within quotes, and uses the parenthesis to use the bit within them to be part of the substitution. \1 stands for the first bit between parenthesis block; \2 for the second.

You could of course make the search more robust to cope with whitespace between the tag and the equal sign and so on.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download