Never been to CodeSnippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

1 total

Basic examples of using associative arrays in awk

# example 1

text='Jex Mon clerk 12001
Aji Tue sales 13003
Jex Wed clerk 13123
Salna Thu sales 34000
Aji Mon sales 13123'

# count the number of occurrences of each "first field"
echo "$text" | awk '{count[$1]++}END{for(j in count) print j,count[j]}'

# sum up the fourth field
echo "$text" | awk '{arr[$1]+=$4} END {for (i in arr) {print i,arr[i]}}'

# both in one line
echo "$text" | awk '{a[$1]++;b[$1]=b[$1]+$NF}END{for (i in a) print i,a[i],b[i]}' 


# example 2

awk -F "|" 'NR > 1  {
    if (n[$1] == $1) {
        r1[$1] = r1[$1] "+" $2
        r2[$1] = r2[$1] "+" $3

    } else {
        n[$1] = $1
        r1[$1] = $2
        r2[$1] = $3

    }
}

END {
    for (i in n) {
            printf "%s [Round1={%s}, Round2={%s}]\n", n[i], r1[i], r2[i]
    }
}'   < <( 
cat <<-'EOF'
Name|Round1|Round2
JSingh|0|20
Vis|50|0
KKR|20|20
JSingh|10|40
Vis|50|20
KKR|40|10
JSingh|40|60
Vis|30|20
KKR|90|20
JSingh|0|60
Vis|20|20
KKR|50|50
EOF
)


References:

- Associative array in awk (example 1)
- Print individual records using awk array - bash (example 2)
- Arrays in awk
- Working with Arrays in awk
1 total