数字和数字用awk之间的转换个月 [英] Converting months between numeric and number using awk

查看:378
本文介绍了数字和数字用awk之间的转换个月的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在准备考试过去的论文中,我有一个问题:

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

月可以重新$ P $,例如作为数字
  (1,2,...,12),或作为三字母月份名称(一月,二月,...,分解)。
  建议如何关联数组在awk中可以用来从翻译
  三个字母的月份名称为月数,反之亦然,以
  一个月的数字转换为三个字母的月份名称。

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.

所以我想我会在格式使用关联数组表示,本月的输入是$ 1:

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.

我有什么其他选择?

推荐答案

的内置拆分的功能在这里你的朋友,循环可以复制名称从数版本成数从名称:

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]
    }
}

BEGIN 块展示了如何做到这一点。然后 END 块只是让你验证。

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

我得到(使用GAWK 4.0.1)的输出是:

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

注意平时的尴尬(嘿!尴尬的),从无力迫使阵列的访问顺序为循环arrising。

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

这篇关于数字和数字用awk之间的转换个月的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆