2

I have many files, all having the same number of rows, all having the same values in column 1 (which I want to keep). The problem is the output changes the order.

cat file1.dat
Sep-12 1082
Oct-12 1377
Nov-12 1095
Dec-12 888
Jan-13 1184
Feb-13 1036
Mar-13 895
Apr-13 1207
May-13 1325
Jun-13 1147
Jul-13 1256
Aug-13 1362
Sep-13 1260

cat file2.dat
Sep-12 5185
Oct-12 5707
Nov-12 5427
Dec-12 3321
Jan-13 8093
Feb-13 6000
Mar-13 6348
Apr-13 6921
May-13 6959
Jun-13 6246
Jul-13 6634
Aug-13 6704
Sep-13 6350

.....etc

when I run

awk '{a[$1]+=$2}END{for (k in a) print k,a[k]}' dat_files/*.dat

I get

May-13 20086
Nov-12 16175
Jun-13 74138
Mar-13 16598
Jan-13 18293
Aug-13 21853
Feb-13 14831
Jul-13 20614
Sep-12 12480
Sep-13 20717
Oct-12 14099
Apr-13 23954
Dec-12 11469

which seems to be in no particular order (and not what I want). I would like the output to be in the same order as all the .dat files, i.e. starting with

Sep-12 (total)
Oct-12 (total)
Nov-12 (total)
etc...

I thought awk read the data in each file in order...? Any help would be appreciated. Thanks!

4

3 に答える 3

4

連想配列は、キーの挿入順序を保持しません。これはほとんどの言語に当てはまります。

列名の順序を別の配列に保存し、それを使用して結果を出力できます。

awk '
    {
        s[FNR] += $2
        c[FNR] = $1
    }

    END {
        for (i=1; i <= FNR; i++)
            print c[i], s[i]
    }
' dat_files/*.dat
于 2013-10-08T17:23:57.870 に答える
0

合計を取得したら、名前を付けますall.dat。次に、次のことを試すことができます

awk 'BEGIN {j = 0} { if (content[$1] != "" ) { content2[j $1] = $0 ; j++ ; } else { content[$1] = $0 ; }  } END { for ( i in content2 ) print i, content2[i] ; } ' file1.dat all.dat 
| sort 
| awk '{ $1="" ; print ; }'

このスクリプトは、人為的な列を追加してsortから削除します。

于 2013-10-08T17:17:58.363 に答える