简体   繁体   中英

AWK command for sum 2 files

i am new at awk and i need awk command to summing 2 files if found the same column

file 1

a | 16:00 | 24
b | 16:00 | 12
c | 16:00 | 32

file 2

b | 16:00 | 10
c | 16:00 | 5
d | 16:00 | 14

and the output should be

a | 16:00 | 24
b | 16:00 | 22
c | 16:00 | 37
d | 16:00 | 14

i have read some of the question here and still found the correct way to do it, i already tried with this command

awk 'BEGIN { FS = "," } ; FNR=NR{a[$1]=$2 FS $3;next}{print $0,a[$1]}'

please help me, thank you

This script also uses sort but it will work,

awk -F'|'  ' { f[$1] += $3 ; g[$1] = $2 } END { for (a in f) { print a , "|",  g[a] , "|",  f[a] } } '   a.txt b.txt | sort

The results are

    a  |  16:00  | 24
    b  |  16:00  | 22
    c  |  16:00  | 37
    d  |  16:00  | 14

|sort

awk -F'|' '{O[$1FS$2]+=$3}END{asorti(O,T,"@ind_str_asc");for(t in T)print T[t] FS O[T[t]]}' file[1,2]

Just store all the data in two arrays a[] and b[] and then print them back:

awk 'BEGIN{FS=OFS="|"}
     {a[$1]+=$3; b[$1]=$2}
     END{for (i in a) print i,b[i],a[i]}' f1 f2

Test

$ awk 'BEGIN{FS=OFS="|"} {a[$1]+=$3; b[$1]=$2} END{for (i in a) print i,b[i],a[i]}' f1 f2
b | 16:00 |22
c | 16:00 |37
d | 16:00 |14
a | 16:00 |24

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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