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
2009-12-03 20:37:56
Is this a Linux extension? Neither FreeBSD or Mac OSX seem to support it.
D.Shawley
2009-12-03 20:57:16
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
2009-12-03 21:10:40
+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
2009-12-03 20:40:09
A:
have you tried using cut?
something like this:
dayofweek=date|cut -d" " -f1
Jay
2009-12-03 20:41:44
That only separates the date and the time, not each part individually.
Dennis Williamson
2009-12-03 21:34:20
+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
2009-12-03 21:43:01
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
2009-12-04 08:08:29
+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
2009-12-06 03:40:20
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
2009-12-06 03:45:58
+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
2009-12-06 04:01:10
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
2009-12-06 06:00:59