Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting months between numeric and number using awk

In a past paper for an exam I have the question:

Months can be represented in different ways, for example as numbers (1, 2, …, 12), or as three- letter month names (Jan, Feb, …, Dec). Suggest how associative arrays in awk can be used to translate from three-letter month names to month numbers, and vice versa, to translate month numbers to three-letter month names.

So I thought I would use associative arrays in the format say the input of the month is in $1:

number_to_month["Jan"] = 1;
print number_to_month[$1]

But to me this doesn't seem to leverage the power of associative arrays very well, plus I have to initialise each month in the array manually.

What are my other options?

like image 412
BradStevenson Avatar asked Sep 01 '25 10:09

BradStevenson


1 Answers

The builtin split function is your friend here, and looping can copy the name-from-number version into the number-from-name:

BEGIN {
    split("Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec",month)
    for (i in month) {
        month_nums[month[i]]=i
    }
}
END {
    for (i in month) {
        print i "\t" month[i]
    }
    for (m in month_nums) {
        print m "\t" month_nums[m]
    }
}

The BEGIN block shows how to do it. Then END block just lets you verify it.

The output I get (using gawk 4.0.1) is:

4       Apr
5       May
6       Jun
7       Jul
8       Aug
9       Sep
10      Oct
11      Nov
12      Dec
1       Jan
2       Feb
3       Mar
Feb     2
Sep     9
Jan     1
May     5
Apr     4
Oct     10
Dec     12
Nov     11
Jul     7
Mar     3
Aug     8
Jun     6

notice the usual awkwardness (Heh! AWKwardness) arrising from the inability to force the access order on array for loops.

like image 158
dmckee --- ex-moderator kitten Avatar answered Sep 03 '25 23:09

dmckee --- ex-moderator kitten