我正在编写一个脚本来处理配置文件的输出,从而产生有值(value)的数据。
输出的格式为:
[header]
attribute1 = integer
attribute2 = integer
[header]
attribute1 = integer
attribute2 = integer
...
可能存在未知数量的具有相同两个属性(具有未知整数值)但具有不同 header 的节。
到目前为止,我只能生成不同节的数量以将其用作循环计数器,但我不确定如何循环输出,保持标题不变,但将两个属性的整数值相加,并将它们替换为新属性,例如,
[header]
new_attribute = integer
[header]
new_attribute = integer
我已经研究了命令read
,但我不确定如何用它生成我想要的报告。
最佳答案
请不要使用shell批量处理文本文件;它既缓慢又不安全。我最喜欢的文本处理工具是 Awk,您可以通过 man awk
了解更多信息。
在 awk 中,NR
指的是编号记录,或行号。 %
是“模”或余数,所以如果我们知道只有三种记录,我们就可以非常直白地写出想要的脚本。
尝试 awk '{print NR%3, $0}' file
查看结构。
awk -F ' = ' ' # Field Separator = space, equals, space
NR%3 == 1 {print $0} # print header
NR%3 == 2 {i=$2} # save second field as i
NR%3 == 0 {print "new_attribute" FS i+$2} # print string, field separator, and sum
' file
关于linux - 如何循环输出并将结果格式化为新报告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56433685/