总和每80行一条线尴尬



我有一个非常大的文本文件,该文件是数字的向量,我想将80行添加在一起,将结果打印在新文件中,然后取第二条81-160行,将它们添加并在新文件的下一行中打印结果,依此类推,直到文件结束。

请注意,行的数量不一定是80的倍数,因此对于最后一行,我必须添加剩余的行。

可以使用尴尬或类似的编程语言快速地进行此操作吗?

谢谢。

Note2:文件看起来像这样:

3.456
3.4
6.788
9.342
... etc ...

另一个尴尬的单线:

awk '{s+=$0;if( NR%80==0){print s-r;r=s}}END{if(s!=r)print s-r}' file

SEQ 21 和每个 5 线:

测试:
kent$  seq 21|awk '{s+=$0;if(NR%5==0){print s-r;r=s}}END{if(s!=r)print s-r}' 
15
40
65
90
21

我能想到的最短尴尬解决方案是(如果高尔夫球,47个字符):

awk '{ s += $1 } NR % c == 0 { print s; s=0 } END { if(NR % c) print s }' c=80

s累积总和。每80行打印总和,s是重置的。END子句在NR % 80 != 0

上打印最终总和

清洁输出范围:

 awk '{
    if ( NR%80 ){tot+=$0} 
    else{tot+=$0;print tot; tot=0}
   }
   END {if (NR%80 !=0 ) print tot}
 ' file > sumFile

请注意,您可以将80更改为任何值。

调试版本

awk '{
   if ( NR%80 ){
       print "line="$0;tot+=$0} 
   else{
       print "2line="$0;
       tot+=$0;
       print "tot="tot; 
       tot=0
     }
   }
  END {
      if (NR%80!=0) print "2tot="tot
  }' file

ihth。

尝试以下:

#!/bin/bash
awk 'BEGIN {c=0; tot=0};
    {
        tot=tot+$1;
        c++;
        if (c==80) {
            print tot;
            c=0
            tot=0
        }
    };
    END {print tot}'

(测试并起作用)

这是一个perl解决方案:

#!/usr/bin/perl
use strict;
use warnings;
open( my $fh,  '<', 'nums.txt' ) or die $!;
open( my $out, '>', 'res.txt' )  or die $!;
my $sum        = 0;
my $line_count = 1;
while (<$fh>) {
    $line_count++;
    chomp;
    $sum += $_;
    if ( $line_count == 80 or eof($fh) ) {
        print $out "$sumn";
        $line_count = 0;
        $sum        = 0;
    }
}
close($fh);
close($out);

文件名也取决于您。它将打印前80行的总和,然后连续下一条新线。

最新更新