简体   繁体   English

如何从 100 个文件中求和 - bash/awk?

[英]How to sum from 100 file - bash/awk?

I need to sum up values from 100 files.我需要总结 100 个文件中的值。 This is part of my input suma_wiazan_wodorowych_2_1.txt这是我输入的一部分 suma_wiazan_wodorowych_2_1.txt

2536
1928
1830
1774
1732
1673
1620

suma_wiazan_wodorowych_2_101.txt (name for every file is changing by 100, so 1, 101, 201 etc) suma_wiazan_wodorowych_2_101.txt(每个文件的名称都改变了 100,所以 1、101、201 等)

2535
1987
1895
1829
1805
1714
1657

So my script should add first row from the first file first row from the second file.... to one hundred 2535+2536+..+..+2621 And against the second row from the first + second row from the second file etc. The length of every file is 5000 rows (so I will have 5000 sums) Do you have any idea?所以我的脚本应该将第一个文件的第一行从第二个文件的第一行添加到一百个 2535+2536+..+..+2621 并针对第二个文件的第一行的第二行+第二个文件的第二行等等。每个文件的长度是 5000 行(所以我会有 5000 个总和)你知道吗?

A one-liner using paste and bc使用pastebc的单线

paste -d + suma_wiazan_wodorowych_2_* | bc

assuming the lines contain only bare numbers without a leading + (negative numbers, that are, numbers with a single leading - , are ok), and the files have equal number of lines.假设这些行仅包含没有前导+的裸数字(负数,即带有单个前导-的数字是可以的),并且文件具有相同数量的行。

with awkawk

$ awk '{sum[FNR]+=$1} END{for(i=1;i<=FNR;i++) print sum[i]}' file*

sum all corresponding values from all input files, print at the end.将所有输入文件中的所有对应值相加,最后打印。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM