tags:

views:

46

answers:

3
   @ubuntu:/tmp$ cat one.xml 
<?xml version="1.0" encoding="UTF-8"?>
    <e2frontendstatus> 
     <e2snrdb>
      12.10 dB
     </e2snrdb>
     <e2snr>
      75 %
     </e2snr>
     <e2ber>
      0
     </e2ber>
     <e2acg>
      99 %
     </e2acg>
    </e2frontendstatus>
   @ubuntu:/tmp$ sed -n -e 's/.*<e2ber>\([0-9][0-9]*\)<\/e2ber>.*/\1/p' one.xml 
   @ubuntu:/tmp$ 

I want to get the value betwen . But it's not working, what I am doing wrong?

+2  A: 

Processing xml with regular expressions is not a very good idea, you might want to look into a command line tool like xmlstarlet to do this extraction.

xmlstarlet sel -t -v "//e2ber" one.xml
Jörn Horstmann
Thank you for the answer, but I run this little command on an embedded system (satellite receiver), where is not possible to run xmlstarlet (which is a very nice tool) :/ .All other linux command is available, grep, sed..
Peter
Can you install xmllint?
reinierpost
reinerpost: Nothing :|
Peter
A: 

What value are you looking for? Do you know that Linux's grep has an "After context" and "Before Context" command line parameters? That might be the easiest way of pulling of the information you're looking for.

For example, if you're trying to get the value after the line , you could do something like this:

$ grep -A1 "<e2ber>" | tail -1
David W.
Simple, and works like a charm!! Thank you very much!
Peter
+1  A: 

If you have the grep -A option mentioned in the above answer, and the Unix command tr on your system, you can make something reasonably robust.

This command should get the appropriate value:

grep -A2 '<e2ber>' one.xml | \
    tr -d '\n' | \
    sed -n -E -e 's/.*<e2ber>[[:blank:]]*([0-9][0-9]*)[[:blank:]]*<\/e2ber>.*/\1/p'

This should work whether the XML file is formatted as <e2ber>0</e2ber> or as

<e2ber>
    0
</e2ber>

The grep will grab enough lines to include the closing tag, the tr will make this one long line, and the sed will extract the value. I've updated the regular expression in the sed to ignore whitespace around the value.

This may still have problems if the XML file is double spaced -e.g.

<e2ber>

0

</e2ber>

You can get round this by running the XML file through tr -s '\n' beforehand. This will compact multiple newlines into a single newline.

Pat Wallace