AWK Easy · Lesson 1 · On the house

Multidimensional arrays and SUBSEP

Simulate matrices with a[i,j], understand SUBSEP, split compound keys, and walk rows and columns safely. Lesson 1 is free — on the house.

Lessons · AWK Easy · Lesson 1 of 10 · On the house

Multidimensional arrays and SUBSEP

Simulate matrices with a[i,j], understand SUBSEP, split compound keys, and walk rows and columns safely.

Illustration for AWK
Lesson 1 is on the house.

AWK has only one-dimensional arrays. Writing a[i, j] builds a single string key by joining the subscripts with the built-in string SUBSEP (ASCII 0x1c by default). So a[2, 3] is the same element as a[2 SUBSEP 3].

((i, j) in a) tests for that compound key without creating it. Reading a[i, j] when it is missing creates an empty element, just as with ordinary keys.

You can put more than two subscripts in the list: cube[x, y, z]. The same SUBSEP joining applies. Keep SUBSEP out of your own data, or set it to a character that never appears in the subscripts before you fill the array.

To recover the parts of a key from for (k in a), call split(k, parts, SUBSEP). parts[1] is the first subscript, parts[2] the second, and so on. for-in order is still unspecified, so sort when the order of output matters.

Nested counting loops are the reliable way to walk a dense matrix: outer loop over rows, inner over columns, and ((i, j) in m) to skip holes. That pattern does not depend on for-in order.

A sparse table, such as a word co-occurrence count keyed by (left, right), stores only the cells you touch. Memory grows with the number of pairs seen, not with the full rectangle of possible pairs.

multi.awk

# multi.awk : gawk -f multi.awk
BEGIN {
    print length(SUBSEP)                    # default SUBSEP is one character
    m[1, 1] = 10; m[1, 2] = 20
    m[2, 1] = 30; m[2, 2] = 40
    print m[1, 2], m[2 SUBSEP 1]            # both forms name the same cells
    print ((1, 2) in m), ((3, 1) in m)      # in does not create a key
    for (i = 1; i <= 2; i++) {
        for (j = 1; j <= 2; j++)
            printf "%d ", m[i, j]
        print ""
    }
    pair["tea", "mug"] = 3
    pair["tea", "cup"] = 1
    pair["coffee", "mug"] = 5
    for (k in pair)                         # collect "left right count" lines
        print k, pair[k] | "sort"
    close("sort")
    # show how split recovers the subscripts of one known key
    key = "tea" SUBSEP "mug"
    split(key, ij, SUBSEP)
    print "parts:", ij[1], ij[2], "value:", pair[ij[1], ij[2]]
}
Match this when you type.

Quiz

What does a[2, 3] actually store as its key?

Quiz

How do you test for a[i, j] without creating it?

Quiz

How do you recover the parts of a compound key k?

Quiz

Why prefer nested for-i/for-j loops over for-in for a dense matrix?

Check

Match the still for: Multidimensional arrays and SUBSEP.

Open-book: the answers are on this page. Pass every quiz and check (5) to mark the lesson done. This visit: 0/5.