简体   繁体   English

Linux shell脚本 - 获取String中的数字总和,同时保留String的总和数

[英]Linux shell scripting - Getting the sum of numbers within a String but also keeping the String with the sum number

I have an xml file that has numbers within tags. 我有一个xml文件,其中包含标签内的数字。 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. 我已经使用awk删除标签并添加数字,但这不是我想要的。 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? 我正在做的是替换,如果我只得到数字,那么替换也将替换该文件中等于的所有其他数字,而不仅仅是REC_CNT ...任何输入?

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. 根据需要调整正则表达式。

您应该使用实际的XML处理器而不是基于正则表达式的文本管理工具。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM