Awk:在原始值旁边打印累计和

时间:2019-07-03 18:59:39

标签: awk

输入文本文件包含4个字段,它们之间用|分隔。如此处所示:

Name|Payment|Date|-900
Name|Invoice|Date|900
Name|Payment|Date|-900
Name|Invoice|Date|900
Name|Payment|Date|-900
Name|Invoice|Date|900
Name|Payment|Date|-900
Name|Invoice|Date|900
Name|Payment|Date|-900
Name|Invoice|Date|900

以下脚本的目的是在$ 5中打印$ 4的累积金额。即在每行的原始值$ 4旁边,打印所有上述值的总和。

正如您在下面的实际输出中看到的那样,已经实现了累加的总和,但是脚本中的某些操作导致输入文件的每一行都打印在预期输出的每一行下方。

    $ awk -F '|' '{total += $4; print $0"|",total}1' infile.txt

预期输出:

Name|Payment|Date|-900|-900
Name|Invoice|Date|900|0
Name|Payment|Date|-900|-900
Name|Invoice|Date|900|0
Name|Payment|Date|-900|-900
Name|Invoice|Date|900|0
Name|Payment|Date|-900|-900
Name|Invoice|Date|900|0
Name|Payment|Date|-900|-900
Name|Invoice|Date|900|0

实际输出:

Name|Payment|Date|-900| -900
Name|Payment|Date|-900
Name|Invoice|Date|900| 0
Name|Invoice|Date|900
Name|Payment|Date|-900| -900
Name|Payment|Date|-900
Name|Invoice|Date|900| 0
Name|Invoice|Date|900
Name|Payment|Date|-900| -900
Name|Payment|Date|-900
Name|Invoice|Date|900| 0
Name|Invoice|Date|900
Name|Payment|Date|-900| -900
Name|Payment|Date|-900
Name|Invoice|Date|900| 0
Name|Invoice|Date|900
Name|Payment|Date|-900| -900
Name|Payment|Date|-900
Name|Invoice|Date|900| 0
Name|Invoice|Date|900

1 个答案:

答案 0 :(得分:2)

$ awk -F'|' '{___+=$NF; print $0 FS ___}' file

Name|Payment|Date|-900|-900
Name|Invoice|Date|900|0
Name|Payment|Date|-900|-900
Name|Invoice|Date|900|0
Name|Payment|Date|-900|-900
Name|Invoice|Date|900|0
Name|Payment|Date|-900|-900
Name|Invoice|Date|900|0
Name|Payment|Date|-900|-900
Name|Invoice|Date|900|0