2
Is there a way to convert month number to name with a script?
example:
2013-10-22
will become Oct 22
Thanks.
BTW, I don't have the GNU date and my OS is AIX.
2
Is there a way to convert month number to name with a script?
example:
2013-10-22
will become Oct 22
Thanks.
BTW, I don't have the GNU date and my OS is AIX.
1
You should have a usable awk
(or nawk
):
BEGIN {
nmon=split("Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec",month)
for(mm=1;mm<=nmon;mm++) {
month[month[mm]]=mm
month[sprintf("%02i",mm)]=month[mm]
}
}
/[12][0-9][0-9][0-9]-[0-1][0-9]-[0-3][0-9]/ {
split($1,bits,/-/)
printf("%s %02i\n",month[bits[2]],bits[3])
}
The BEGIN{}
block creates a mapping hash. It's a bit more general purpose than you strictly need (I just happen to have it laying around), its indexes are the short-name, the month ordinal (number) and the two-digit month ordinal with a leading zero. This means you can convert name to number or vice versa. You can easily adapt it for long month names too (and possibly localisation, but let's not get carried away).
The next block looks for lines containing a likely looking date string, splits on "-" and converts the date. (This also works in gawk
, but if you happen to have that, then strftime()
and mktime()
are a more elegant solution.)
A basic ksh
shell version, since AIX has ksh
:
set -A month pad Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
while IFS=- read yyyy mm dd junk; do
echo ${month[$mm]}
done
This uses an array (POSIX sh
does not have arrays, bash
does, so you may do something similar with it too). Note that this relies on ksh
to handle the leading 0 in a month number, it just treats it as an integer. Since ksh
(and bash
) arrays are zero based, we stuff a dummy "pad" value into index 0 rather than play with +1/-1 on indexes.
1
date +"%B %d"
Will display January 1
date +"%b %d"
Will display Jan 1