Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unix convert Month name to number

Tags:

shell

unix

awk

In BASH shell scripting or using gdate, given a date like "Oct 2011" how do I convert to a year-month number format? Output should be "2011-10", for example.

like image 623
Dan Avatar asked Mar 06 '13 16:03

Dan


2 Answers

mydate="Oct 2011"
date --date="$(printf "01 %s" $mydate)" +"%Y-%m"

The parse_datetime interface for GNU date (which is what the example uses) has lots of rules. the Oct 2011 form of the date isn't one of them, so you prepend a "01 " to the front of it and date likes it.

like image 141
jim mcnamara Avatar answered Nov 19 '22 09:11

jim mcnamara


read mon year <<< "Oct 2012"
date -d "$mon 1 $year" "+%Y-%m"

Result:

2012-10
like image 10
Davide Berra Avatar answered Nov 19 '22 11:11

Davide Berra