I want to change a date from format dd-mmm-yyyy to mm/dd/yyyy. Is there a way to do this with sed or do you have to write a case statement to convert JAN to 01? Thanks
On FreeBSD:
date -j -f "%d-%b-%Y" "27-Mar-2008" "+%m/%d/%Y"
Maybe I should have mentioned that I am using korn shell. I get an error when using that.
> date "%d-%b-%Y" "27-Mar-2008" "+%m/%d/%Y"
date: bad conversion
Next time you should mention your shell and your OS from the beginning
echo "28-Mar-2008" | date -d - "+%m/%d/%Y"
or..
#!/bin/ksh
d="28-Mar-2008"
date -d $d "+%m/%d/%Y"
You should take a look over man date anyway.
Not all date implementations have all this fancy shmancy stuff. As a matter of fact, on HP-UX or Sun, you should be thankful that it even displays today's date.
If you can't get a good date (sorry, couldn't resist), then yes, sed (or cut, or awk, or perl, or nearly any programming language you happen to know the basics of) can be used to move around parts within the string.
(True story from real life: I had a colleague who needed to remove duplicate lines from a file. I intercepted him when he had exported the file to his University account and loaded it into SPSS which he was more familiar with, but couldn't quite get to do this precise task.)
But yes, you need the month name to number mapping somehow. somebody posted one awk solution the other day, but I can't seem to find it now. If the input is just the date then twelve lines of sed will do it.
# echo "dd-mmm-yyyy" | awk 'BEGIN{FS="-";OFS="/"}{print $2,$1,$3}'
mmm/dd/yyyy
Add to the BEGIN { m[jan] = 1; m[feb] = 2; ... etc } and there you have it. Like I said, somebody posted code like this I think only yesterday, but I wasn't able to bring it up with a search.
If you are using ksh93 version h or later (echo ${.sh.version} to see version details, h has been available since 1999) and not ksh88 or pdksh, then use the printf %T option to change the date format.
$ printf "%(%m/%d/%Y)T" "28-Mar-2008"
03/28/2008
Could u post the complete awk statement that can be used to convert JAN to 01 and so on?
thanks
Here you can find an example:
Regards