tags:

views:

971

answers:

8
+2  Q: 

Parse Date in Bash

I need to parse a date (format: YYYY-MM-DD hh:mm:ss) in bash. I'd like to end up with all fields (years, months, days, hours, minutes, seconds) in different variables.

+3  A: 

Does it have to be bash? You can use the /bin/date binary for many transformations:

 $ date --date="2009-01-02 03:04:05" "+%d %B of %Y at %H:%M and %S seconds"
 02 January of 2009 at 03:04 and 05 seconds

This parses the given date and displays it in the chosen format. You can adapt that at will to your needs.

Dirk Eddelbuettel
Is this a Linux extension? Neither FreeBSD or Mac OSX seem to support it.
D.Shawley
It's plain old GNU date:$ date --versiondate (GNU coreutils) 7.4Copyright (C) 2009 Free Software Foundation, Inc.License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.This is free software: you are free to change and redistribute it.There is NO WARRANTY, to the extent permitted by law.Written by David MacKenzie.
Dirk Eddelbuettel
+4  A: 
$ t='2009-12-03 12:38:15'
$ a=(`echo $t | sed -e 's/[:-]/ /g'`)
$ echo ${a[*]}
2009 12 03 12 38 15
$ echo ${a[3]}
12
DigitalRoss
no need to call external command
A: 

have you tried using cut? something like this: dayofweek=date|cut -d" " -f1

Jay
That only separates the date and the time, not each part individually.
Dennis Williamson
+2  A: 

Pure Bash:

date="2009-12-03 15:35:11"
saveIFS="$IFS"
IFS="- :"
date=($date)
IFS="$saveIFS"
for field in "${date[@]}"
do
    echo $field
done

2009
12
03
15
35
11
Dennis Williamson
No need to use arrays here. Just `set junk $date; shift` instead of `date=($date)` and `for field` instead of the array loop. That would be a `pure sh` version, which is even better!
Idelic
+2  A: 

another pure bash

$ d="2009-12-03 15:35:11"
$ d=${d//[- :]/|}
$ IFS="|"
$ set -- $d
$ echo $1
2009
$ echo $2
12
$ echo $@
2009 12 03 15 35 11
+1  A: 

The array method is perhaps better, but this is what you were specifically asking for:

IFS=" :-"
read year month day hour minute second < <(echo "YYYY-MM-DD hh:mm:ss")
Steve Baker
I like this best. One shortcut, which also doesn't permanently change IFS: `IFS=" :-" read Y M D h m s <<<"YYYY-MM-DD hh:mm:ss"`
ephemient
+3  A: 

This is simple, just convert your dashes and colons to a space (no need to change IFS) and use 'read' all on one line:

read Y M D h m s <<< ${date//[-:]/ }

For example:

$ date=$(date +'%Y-%m-%d %H:%M:%S')
$ read Y M D h m s <<< ${date//[-: ]/ }
$ echo "Y=$Y, m=$m"
Y=2009, m=57
NVRAM
`${date//[-:]/ }` would work too: replacing a space with a space is pointless :D
ephemient
Indeed, I noticed that yesterday but didn't bother editing it until now.
NVRAM
A: 

instead of using the shell scripting,incorporate in your scripting itself like below wheever you need:

a=date +%Y 
b=date +%S
c=date +%H

a will be year b will be seconds c will be hours. and so on.

Vijay Sarathi