hi all,
i am new to shell scripting and need help.
i have a string that stores the month in Jan/Feb/Mar format. i need to convert it to number like 01 for jan, 12 for dec etc.
i am using the following sed command,
echo "Enter a Month eg. Jan/Feb : "
read MONTHEND
MTS=`echo $MONTHEND | sed 's/Jan/01/'`
MTS=`echo $MONTHEND | sed 's/Feb/02/'`
MTS = `echo $MONTHEND | sed 's/Mar/03/'`
MTS = `echo $MONTHEND | sed 's/Apr/04/'`
MTS = `echo $MONTHEND | sed 's/May/05/'`
MTS = `echo $MONTHEND | sed 's/Jun/06/'`
MTS = `echo $MONTHEND | sed 's/Jul/07/'`
MTS = `echo $MONTHEND | sed 's/Aug/08/'`
MTS = `echo $MONTHEND | sed 's/Sep/09/'`
MTS = `echo $MONTHEND | sed 's/Oct/10/'`
MTS = `echo $MONTHEND | sed 's/Nov/11/'`
MTS = `echo $MONTHEND | sed 's/Dec/12/'`
echo $MTS
But it is only working if i give Dec as input. For other months it is returning the month in words itself. please help and suggest a better way.
Take a look at your code again, what is the last action it performs, regardless of the month entered?
Perhaps you need to perform a check for the value of month and make the substitution conditional otherwise the result is always the output of the final line.
That's because you are using the $MONTHEND var in each assignment. The last one always gets assigned to MTS. You should change the $MONTHEND to $MTS and start with assigning $MONTHEND to MTS (ie. 1st line => MTS=$MONTHEND)
@Franklin52
You are right. Using 1 awk statement instead of 12 sed commands is much more efficient, but could you explain how this command works in this case. I'm sure its pretty simple, but it looks a little complex. Thanks
MTS=$(awk -v m=$MONTHEND 'BEGIN{printf( "%.2i\n",index(" JanFebMarAprMayJunJulAugSepOctNovDec", m )/3 )}')
The index() function returns the index of m (the given month) in the string of the 1st parameter.
The length of the month name is 3 and the index of the 1st month is 3, for the 2nd month 6 etc.
"Jan" gives 3; the month number is 3/3=1
"Feb" gives 6; the month number is 6/3=2
"Mar" gives 9; the month number is 9/3=3
"Apr" gives 12; the month number is 12/3=4