Saturday, January 26, 2013

How to convet Months names into numbers in bash

So, today i needed a quick way to rename files and folders with names that include month name into a more computer readable numerical presentation.

I wrote a small shell one-liner that does that for me; i pass the file name as a parameter to a script; the script would remove the month name (whether its short (ex Jan) or long (ex November) and would replace it with a two digit number (from 01 to 12) using sed. the script also matches the names regardless of their capitalization (case insensitive) as sed understands "i" for "insensitive".

the script is below:

#!/bin/bash
echo $1 | sed "s/Jan\|January/01/gi;s/Feb\|February/02/gi;s/Mar\|March/03/gi;s/Apr\|April/04/gi;s/May\|May/05/gi;s/Jun\|June/06/gi;s/Jul\|July/07/gi;s/Aug\|August/08/gi;s/Sep\|September/09/gi;s/Oct\|October/10/gi;s/Nov\|November/11/gi;s/Dec\|December/12/gi;"


The script has been auto generated pretty quickly as well, i had a list of the names of months:

January
February
March
April
May
June
July
August
September
October
November


i piped it ino a small loop that matches the first three characters:

echo January | sed "s/^\(...\)/\1\\\|\1/g"

to output
Jan\|January

a shell variable ($cnt) was set to 0 ; and incremented to print the numerical value corresponding to the month (months are in correct order); and was printed using printf:

printf "%02d" $cnt

a while loop glued it togather:

cnt=0
while read line ; cnt=`expr $cnt + 1` ; do echo -n s/ ;echo -n $line |sed "s/^\(...\)/\1\\\|\1/g" ; echo -n / ;printf "%02d" $cnt ; echo -n /gi\; ; done

and the list was pasted as input! viola! a sed pattern is created :)

Now, Egyptians, Syrians, Palestinians, Iraqis and Bahrain's people are being oppressed for the same reason, INEQUALITY imposed by those who do not believe in equality! call it racism, greed, capitalism ...etc.

No comments: