Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove attributes from XML using sed

Tags:

linux

sed

awk

First of all, there might be other (better) options, but I'm bound to sed of awk in this case. I have an XML file with the following contents.

<Field name="field1" type="String">AAAA</Field>
<Field name="field2" type="Integer">0</Field>
<Field name="field4" type="String">BBBB</Field>

Here I would like to change the contents using sed, to get the following result:

<field1>AAAA</field1>
<field2>0</field2>
<field4>BBBB</field4>

So remove the "*Field name="*", the last quote from the name and the rest of the attributes up till the *>* and also I would like to change the last </Field> with the actual field name. How to approach with awk or sed?

Removing from the first tag works with

sed 's/ type=".*"//' 
# and
sed 's/Field name="//' 

I'm not sure how to proceed with the replacing of the last one.

like image 443
Frank Avatar asked Jul 30 '26 08:07

Frank


2 Answers

Using sed

$ sed -E 's~[A-Z][^"]*"([^"]*)[^>]*([^/]*/)[^>]*~\1\2\1~' input_file
<field1>AAAA</field1>
<field2>0</field2>
<field4>BBBB</field4>
like image 97
HatLess Avatar answered Aug 01 '26 22:08

HatLess


Another sed:

sed -E 's/^[^"]+"([^"]+)("[^"]+){2}">([^<]+).*$/<\1>\3<\/\1>/' file.xml
like image 42
Darkman Avatar answered Aug 01 '26 22:08

Darkman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!