1

I have the following block of data and need to extract the percent value in XYZ FREEBYTES, i.e. captured value should be equal to 64. As far as I know, I can grep and cut the data. However, the digits are not fixed. How can I extract the variable percent value in the below block please?

<ab type="global" id="80" totalid="80" intervalms="2150804.595">
    <contraction type="tenured" amount="4325376" newsize="1081330176" timetaken="6.373" reason="space following ab" />
    <finalization objectsqueued="2683" />
    <timesms mark="546.032" sweep="11.013" compact="0.000" total="564.779" />
    <XYZ FREEBYTES="700212376" totalbytes="108133017" percent="64" >
      <abc freebytes="696214000" totalbytes="107700531" percent="64" />
      <efg freebytes="3998376" totalbytes="432486" percent="92" />
    </XYZ>
  </ab>

4 Answers 4

1

You could use GNU grep:

grep -oP 'FREEBYTES.*percent="\K[0-9.]+' file

Or sed:

sed -n '/FREEBYTES/{s/.*percent="\([0-9.]*\).*/\1/p}' file 

Or GNU sed:

sed -rn '/FREEBYTES/{s/.*percent="([0-9.]+).*/\1/p}' file64

Or awk:

awk '/FREEBYTES/{sub(/.*percent="/,""); sub(/".*/,""); print}' file

Or perl:

perl -ne 'print if s/.*FREEBYTES.*percent="([0-9.]+).*/\1/' file

Note that all of these will work on arbitrary input of varying lengths as long as the strings FREEBYTES and percent=" are present and followed by at least one number and then a ".

0
 awk -F[=\"] '/<XYZ FREEBYTES/ {print $9}'

This will find the line with <XYZ FREEBYTES match and print 9th filed with delimiter = and ".

0

any field can be pick up from an XML file, for instance with xyz.xsl having

<?xml version="1.0"?>
 <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:output type="text" />

<xsl:template match="//XYZ">
  <xsl:value-of select="@percent" />
</xsl:template>

</xsl:stylesheet>

a mere xsltproc xyz.xsl foo.xml would yield

<?xml version="1.0"?>




    64

I admit this is a bit longer, and you have to filter out <?xml..> line, however in the ong run xml file are easiest to process.

0

Using XMLstarlet to extract the value of the percent attribute of the XYZ node:

xmlstarlet sel -t -v '//XYZ/@percent' file.xml

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .