LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   Sum numbers in a column in a specific block (http://www.linuxquestions.org/questions/programming-9/sum-numbers-in-a-column-in-a-specific-block-891907/)

Alkass 07-15-2011 11:57 AM

Sum numbers in a column in a specific block
 
Hello experts!

I have files which at some point have a block

</header>
<init>
2212 2212 0.35000000000E+04 0.35000000000E+04 0 0 10042 10042 3 4
0.36900423985E+05 0.32201153339E+02 0.11616800000E+01 3
0.16637486779E+05 0.14518702093E+02 0.11616800000E+01 2
0.41435863992E+04 0.36159004858E+01 0.11616800000E+01 1
0.40250283691E+03 0.35124408261E+00 0.11616800000E+01 0
</init>

So, I want to just add the lines in the first column in the <init> block , but NOT the

2212 2212 0.35000000000E+04 0.35000000000E+04 0 0 10042 10042 3 4

line, ie the first column from the

0.36900423985E+05 0.32201153339E+02 0.11616800000E+01 3
0.16637486779E+05 0.14518702093E+02 0.11616800000E+01 2
0.41435863992E+04 0.36159004858E+01 0.11616800000E+01 1
0.40250283691E+03 0.35124408261E+00 0.11616800000E+01 0

Normally, I would not have problem to do this, but I do not know how to constrain the script to just add the number inside the <init> block . Please note that my numbers are in scientific format, so I would need a similar output, ie not rounding


Thanks in advance

paulsm4 07-15-2011 12:04 PM

I'd strongly consider writing this in Perl or Python.

Since you appear to already be familiar with bash, the learning curve will be minimal.

And since this appears to be an XML file, you'll have no trouble finding an XML library to help you parse the numbers from exactly the subnode(s) you're interested in.

'Hope that helps .. PSM

PS:
Here's one of many good links:
http://www.ibm.com/developerworks/library/xml-perl/

Alkass 07-15-2011 12:22 PM

Well, is not a xml file... is a special scientific format merged product of xml and text... So, let me put it this way, you are aware of a bash command to just constraint the add inside a specific block ?

Thanks again!

grail 07-15-2011 01:12 PM

Well you would need to play with the formatting and it will also depend on whether init can appear more than once:
Code:

awk '/<\/?init>/{x = !x}x{a++}x && a > 2{sum+=$1}END{printf"%E", sum}' file


All times are GMT -5. The time now is 01:14 PM.