bash awk 对一列求和并在输入的每一行上打印该总和

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10510917/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 22:02:07  来源:igfitidea点击:

awk sum a column and print that sum on each line of input

bashsedawkprintf

提问by Steve

My file.txtlooks like this:

我的file.txt看起来像这样:

1 12
2 18
3 45
4 5
5 71
6 96
7 13
8 12

I can sum the second column like this:

我可以像这样总结第二列:

awk '{ sum += $2 } END { print sum }' file.txt

awk '{ sum += $2 } END { print sum }' file.txt

272

272

What's the neatest way that I can print that sum on each line? This is what I'm expecting:

我可以在每一行上打印该总和的最简洁方法是什么?这就是我所期待的:

1 12 272
2 18 272
3 45 272
4 5 272
5 71 272
6 96 272
7 13 272
8 12 272

采纳答案by kev

Kind of standard awkway.

一种标准的awk方式。

$ awk 'FNR==NR{sum+=;next}; {print 
awk -v xyzzy=$(awk '{sum+=}END{print sum}' file.txt)
    '{print 
a 1
b 2
c 3
d 4
e 5
" "xyzzy}' file.txt
,sum}' file.txt{,} 1 12 272 2 18 272 3 45 272 4 5 272 5 71 272 6 96 272 7 13 272 8 12 272

回答by paxdiablo

You can use:

您可以使用:

a 1 15
b 2 15
c 3 15
d 4 15
e 5 15

This unfortunately means going through the information twicebut, since you have to do it once before you get the total, there's no real way around it. Anysolution will involve storing up the information before outputting anything (whether in arrays, or going back to the file).

不幸的是,这意味着要浏览两次信息但是,由于您必须在获得总数之前进行一次,因此没有真正的解决方法。任何解决方案都涉及在输出任何内容之前存储信息(无论是在数组中,还是返回到文件中)。

The inner awkworks out the total and the outer awkassigns that to a variable which can be printed along with each line.

内部计算awk出总数,外部awk将其分配给一个变量,该变量可以与每一行一起打印。

Applying that to the file:

将其应用于文件:

{ 
    a[NR] = 
$ awk -f s.awk file.txt 
1 12 272
2 18 272
3 45 272
4 5 272
5 71 272
6 96 272
7 13 272
8 12 272
sum += } END { for (x = 1; x <= NR; x++) { print a[x], sum } }

gives you, because 1 + 2 + 3 + 4 + 5is equal to 15:

给你,因为1 + 2 + 3 + 4 + 5等于15

perl -nale '$s+=$F[1];push(@a,$_);END{print $_." $s" for(@a);}' file.txt

回答by Fredrik Pihl

Use arrays

使用数组

awk '{printf "%s ", 
$ yes "`<file.txt awk '{ sum +=  } END { print sum }'`" | head -n `<file.txt wc -l` | paste -d ' ' file.txt -
}{system(" awk 7 {sum+=}END{print sum} 7 file ")}' file

Output

输出

##代码##

Read more in Gnu Awk Manual

Gnu Awk 手册中阅读更多内容

回答by codaddict

Offtopic, but in Perl you can do:

Offtopic,但在 Perl 中你可以这样做:

##代码##

回答by Tedee12345

The ugly solution:

丑陋的解决方案:

##代码##

回答by Taku Miyakawa

awk, yes, head and paste.

awk,是的,头部和粘贴。

##代码##