Parse with sed to add double quotes
Hi,
I have been a long time lurkerer and admire what many of you do. I have a little conundrum, I would like to be able to change this text (all in one line): <campaign><cluster><S_NAME>S-cpu</S_NAME><list><A_NODE name=P-3 ltances=1/><A_NODE name=P-4 ltances=2/></list></cluster></campaign> into the following which has double quotes next for the values defined for 'name' and 'ltances': <campaign><cluster><S_NAME>S-cpu</S_NAME><list><A_NODE name="P-3" ltances="1"/><A_NODE name="P-4" ltances="2"/></list></cluster></campaign> What makes this harder is that I have no way of predicting the names used (though it will be quite similar) used for ltance and name, and there can more the just P-3 or P-4 (such as P-5, P-6, etc.) My knowledge of sed is very limited (simple substitutions) and I don't know if its possible to do so, especially considering the whole text is in one line. |
Hi and welcome to LinuxQuestions! :)
Try this: Code:
sed -r 's:name=([^ ]+) ltances=([0-9]+):name="\1" ltances="\2":g' file |
Thanks a bunch!
That did the trick |
A slight variation:
Code:
sed -r 's/=([^ /]*)/="\1"/g' file |
A small correction to grail's post. Since the expression includes a forward slash, you have to change the delimiter to something else.
Code:
sed -r 's%=([^ /]*)%="\1"%g' file (Edit: Hmmm... has sed gotten smarter? It appears not to complain as long as the character in question is inside '[]' brackets. At least the gnu version doesn't. I don't remember it working like that before.) BTW, the above simply adds quotes around anything that appears between an equals-sign and either a space or slash. To avoid false positives you may want to further limit the expression by explicitly addressing the line and the entry names you want to change. Code:
sed -r '/A_NODE/ s%(name|ltances)=([^ /]*)%=\1="\2"%g' file |
All times are GMT -5. The time now is 11:53 PM. |