首页 > 解决方案 > 如何循环输出并将结果格式化为新报告?

问题描述

我正在编写一个脚本来处理配置文件的输出,从而产生有价值的数据。

输出格式为:

[header]
attribute1 = integer
attribute2 = integer
[header]
attribute1 = integer
attribute2 = integer
...

可能有未知数量的节具有相同的两个属性(具有未知的整数值),但具有不同的标题。

到目前为止,我只能生成不同节的数量以将其用作循环计数器,但我不确定如何循环输出,保持标题不变,但将两个属性的整数值相加并替换这些具有总和的新属性,例如,

[header]
new_attribute = integer
[header]
new_attribute = integer

我已经查看了该命令read,但我不确定如何使用它生成我想要的报告。

标签: linuxbashshell

解决方案


while read header &&
      read name1 equal value1 &&
      read name2 equal value2
do
    echo "$header"
    echo "new_attribute = $((value1 + value2))"
done < input.cfg > output.cfg

此代码假定输入完全符合禁止的格式。它不能稳健地处理错误输入:格式错误的行、丢失的行、意外的反斜杠等。


推荐阅读