foo.txt
:
Lillypaul_sg
204803
204803
204803
Ammy_sg
3
ramaswamy_sg
3
33
tommy_sg
3
3
137374
100
期望Out.txt
:
Lillypaul_sg
614409
Ammy_sg
3
ramaswamy_sg
36
tommy_sg
137480
输出是输入文件中的值的总和。标头可能包含字母数字值,但始终以“_sg”结尾。
答案1
awk '$0 == $0+0{
summ += $0
next}
{
if(summ)
format="%06d\n%s\n"
else
format="%s%s\n"
printf format, summ, $0
summ=""}
END {
if(summ)
printf "%06d\n", summ}' foo.txt
答案2
在 Perl 中:
$ perl -lne 'if(/_sg/){print "$n\n$s" if defined($n); $n=$_; $s=0;}
else{$s+=$_}END{print "$n\n$s"}' file
Lillypaul_sg
614409
Ammy_sg
3
ramaswamy_sg
36
tommy_sg
137480
如果您希望数字少于 6 位时用 0 填充(如您原来的问题所示):
$ perl -lne 'if(/_sg/){printf "%s\n%0.6d\n",$n,$s if defined($n); $n=$_; $s=0;}
else{$s+=$_}END{printf "%s\n%0.6d\n",$n,$s}' file