有没有默认键就可以链接2个数组的方法吗?

时间:2019-06-03 18:02:22

标签: arrays awk associative

这是我正在尝试脚本的.txt文件中的内容:

-2 -2 -4 -2 50
-2 -4 -1 -7 20
-5 -6 -1 -8 50
23 -2 -5 -8 -2
5 -2 -1 -1 -5
-8 -3 -5 -6 1
-5 23 -21 -5 -6
-2 -6 -9 34 -21
-2 -3 -4 -5 -6
-1 -3 -5 -8 9
10 -6 -7 -9 2
-10 -45 -21 -5 -10

正确的结果应该是:

Jan -10
Feb -14
mar -20
etc

#!/usr/bin/awk -f

BEGIN {
print "Month ------------- Negative budget"
}

{
sum=0
for(i=1; i<=NF; i++){
    if($i<0){
        sum = sum + $i
    }
}

n=split("Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec", months)
}

{
SM[key]=sum
}

{
for(i=1; i<=n; i++)
    print months[i], SM[key]

}


Month ------------- Negative budget
Jan -10
Feb -10
Mar -10
Apr -10
May -10
Jun -10
Jul -10
Aug -10
Sep -10
Oct -10
Nov -10
Dec -10
Jan -14
Feb -14
Mar -14
Apr -14
May -14
Jun -14
Jul -14
Aug -14
Sep -14
Oct -14
Nov -14
Dec -14
Jan -20
Feb -20
Mar -20
Apr -20
May -20
Jun -20
Jul -20
Aug -20
Sep -20
Oct -20
Nov -20
Dec -20
Jan -17
Feb -17
Mar -17
Apr -17
May -17
Jun -17
Jul -17
Aug -17
Sep -17
Oct -17
Nov -17
Dec -17
Jan -9
Feb -9
Mar -9
Apr -9
May -9
Jun -9
Jul -9
Aug -9
Sep -9
Oct -9
Nov -9
Dec -9
Jan -22
Feb -22
Mar -22
Apr -22
May -22
Jun -22
Jul -22
Aug -22
Sep -22
Oct -22
Nov -22
Dec -22
Jan -37
Feb -37
Mar -37
Apr -37
May -37
Jun -37
Jul -37
Aug -37
Sep -37
Oct -37
Nov -37
Dec -37
Jan -38
Feb -38
Mar -38
Apr -38
May -38
Jun -38
Jul -38
Aug -38
Sep -38
Oct -38
Nov -38
Dec -38
Jan -20
Feb -20
Mar -20
Apr -20
May -20
Jun -20
Jul -20
Aug -20
Sep -20
Oct -20
Nov -20
Dec -20
Jan -17
Feb -17
Mar -17
Apr -17
May -17
Jun -17
Jul -17
Aug -17
Sep -17
Oct -17
Nov -17
Dec -17
Jan -22
Feb -22
Mar -22
Apr -22
May -22
Jun -22
Jul -22
Aug -22
Sep -22
Oct -22
Nov -22
Dec -22
Jan -91
Feb -91
Mar -91
Apr -91
May -91
Jun -91
Jul -91
Aug -91
Sep -91
Oct -91
Nov -91
Dec -91

2 个答案:

答案 0 :(得分:2)

您遍历行中的列以获得总和。很好但是,然后您再次遍历各列以打印月份和总计。您只希望为输入的每一行打印一行,因此在一行行的迭代中进行打印显然会产生太多的输出。

您的月份不适合您的列,但确实适合您的行/记录,因此请使用NR(行号)来处理该months数组并打印:

BEGIN {
print "Month ------------- Negative budget"
n=split("Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec", months)
}

{
    sum=0
    for(i=1; i<=NF; i++){
        if($i<0){
            sum = sum + $i
        }
    }

    print months[NR], sum
}

答案 1 :(得分:-1)

另一个版本

echo "-2 -2 -4 -2 50
-2 -4 -1 -7 20
-5 -6 -1 -8 50
23 -2 -5 -8 -2
5 -2 -1 -1 -5
-8 -3 -5 -6 1
-5 23 -21 -5 -6
-2 -6 -9 34 -21
-2 -3 -4 -5 -6
-1 -3 -5 -8 9
10 -6 -7 -9 2
-10 -45 -21 -5 -10" | awk -F' ' '{sum=0;for(i=1;i<NF;i++) if ($i<0) sum+=$i; SM[NR] = sum;} END{n=split("Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec", months); print "Month ------------- Negative budget"; for(i=1; i<=n; i++) print months[i]"\t\t\t "SM[i]}'

欢呼