0

I have an xml file that has numbers within tags. Ex)

<REC_CNT>25000</REC_CNT>
<REC_CNT>25000</REC_CNT>
<REC_CNT>25000</REC_CNT>
<REC_CNT>11767</REC_CNT>

I need to get the sum of these numbers while at the same time the final output has to still have the tags around it.

<REC_CNT>86767</REC_CNT>

I've used awk already to remove the tags and add the numbers but that is not what I'm looking for. What I'm doing is a replace and if I only get the number then the replace will also replace every other number in that file that it is equal to, not just the REC_CNT... any input?

3
  • 1
    need to see your code. Good luck. Commented May 21, 2012 at 20:06
  • Shell is, quite simply the wrong tool for this. Could you explain why you don't want to consider alternative languages (such as Perl or Python)? Commented May 21, 2012 at 20:32
  • newcount=cat $pocfiles | grep '<REC_CNT>' | awk 'BEGIN {FS="<REC_CNT>"} {print substr($2,0)}' | awk 'BEGIN {FS="<"} {print substr($1,0)}' | awk '{SUM += $1} END {print SUM}' I ended up removing the tags, added the numbers, and reformatted my sed statement to only replace the first instance of the number: sed -i "0,/$oldcount/s//$newcount/" Thanks for the help! Commented May 22, 2012 at 15:34

2 Answers 2

3

awk -v FPAT='([A-Z_]+)|([0-9]+)' '{ sum += $2; fname = $1 } END { print "<" fname ">" sum "</" fname ">" }'

This assumes that your tags are uppercase letters or underscores. Adjust the regular expression as appropriate.

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

1 Comment

thanks for the good effort in that reply.. what i ended up doing was just taking out the tags and then reformatting my sed to only replace the specific instance i want. Thanks again.
0

You should use an actual XML processor instead of some regular-expression based text munging tool.

Comments

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.