0

I have a text stream like this
<device nid="05023CA70900" id="1" fblock="-1" type="switch" name="Appliance Home" brand="Google" active="false" energy_lo="427" />
<device nid="0501C1D82300" id="2" fblock="-1" type="switch" name="TELEVISION Home" brand="Google" active="pending" energy_lo="3272" />

from which i would like an output like
05023CA70900@@1@@-1@@switch@@Appliance Home@@Google@@false@@427 0501C1D82300@@2@@-1@@switch@@TELEVISION Home@@Google@@pending@@3272
There are many lines in the input all of which are not writable.

How can we achieve this using awk or sed ?

2
  • Any reason you're parsing XML data using awk/sed? There are specialized tool for this. Commented Jul 16, 2013 at 9:52
  • Using a shell script in an embedded system have very limited resources for the same.i dont have access to any tools on such a barebone of a system. @anubhava Commented Jul 16, 2013 at 9:55

3 Answers 3

1

Following awk should work:

awk -F '"' '$1 == "<device nid=" { printf("%s@@%s@@%s@@%s@@%s@@%s@@%s@@%s\n", 
                    $2, $4, $6, $8, $10, $12, $14, $16)}' file

PS: It is not always best approach to parse XML using awk/sed.

Sign up to request clarification or add additional context in comments.

1 Comment

Works like a charm my friend but just one little bit of help needed.Can we place a filter in awk itself which first detects if the line has a <device nid in the beginnig .Then it will suffice @anubhava
1

Its very simple in perl . So why not use perl ?

perl -lne 'push @a,/\"([\S]*)\"/g;print join "@@",@a;undef @a' your_file

Sample tested:

> cat temp
<device nid="05023CA70900" id="1" fblock="-1" type="switch" name="Appliance Home" brand="Google" active="false"  energy_lo="427" />  
<device nid="0501C1D82300" id="2" fblock="-1" type="switch" name="TELEVISION Home" brand="Google" active="pending"  energy_lo="3272" />  
> perl -lne 'push @a,/\"([\S]*)\"/g;print join "@@",@a;undef @a' temp
05023CA70900@@1@@-1@@switch@@Google@@false@@427
0501C1D82300@@2@@-1@@switch@@Google@@pending@@3272
>

1 Comment

I dont have perl on my embedded device.But anyways thanks for the suggestion. @Vijay
0
awk -F\" -v OFS="@@" '/^<device nid=/ { print $2, $4, $6, $8, $10, $12, $14, $16 }' file

or more generally:

awk -F\" '/^<device nid=/ {for (i=2;i<=NF;i+=2) printf "%s%s",(i==2?"":"@@"),$i; print ""}' file

To address your question in your comment: If you could have a tab in front of <device nid:

awk -F\" '/^\t?<device nid=// ...'

If you meant something else, update your question and provide more representative input.

1 Comment

And if there is a tab in front of the "device nid".Can you please tell how to account for that. @Ed Morton

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.