user4274473
user4274473

Reputation:

How Do I Parse a Date in Shell?

Right Now I am trying to parse the values from my get time and date and break it down by each number

Format of the date/time

#!/bin/bash 
prevDateTime=$(date +'%Y-%m-%d-%H:%M:%S')
echo "${prevDateTime}"

I want to be able to list it out like so

echo "${prevYear}"
echo "${prevMonth}"
echo "${prevDay}"
echo "${prevHour}"
echo "${prevMinute}"
echo "${prevSecond}"

and then like

echo "${prevDate}"
echo "${precTime}"

But I am not sure how to parse out the information any help would be great

Upvotes: 1

Views: 169

Answers (3)

anubhava
anubhava

Reputation: 784958

You can use read command with IFS to break down date components:

prevDateTime=$(date +'%Y-%m-%d-%H:%M:%S')
IFS='-:' read -ra arr <<< "$prevDateTime"

# print array values
declare -p arr
# This outputs
#   declare -a arr='([0]="2015" [1]="05" [2]="21" [3]="10" [4]="24" [5]="28")'

#assign to other variables
prevYear=${arr[0]}
prevMonth=${arr[1]}
prevDay=${arr[2]}
prevHour=${arr[3]}
prevMinute=${arr[4]}
prevSecond=${arr[5]}

Upvotes: 1

Pavel  Krasavin
Pavel Krasavin

Reputation: 175

Fast solution using cut:

#!/bin/bash 
prevDateTime=$(date +'%Y-%m-%d-%H:%M:%S')
echo "${prevDateTime}"

prevYear=`echo $prevDateTime | cut -d- -f1`
prevMonth=`echo $prevDateTime | cut -d- -f2`
prevDay=`echo $prevDateTime | cut -d- -f3`
prevHour=`echo $prevDateTime | cut -d- -f4 | cut -d: -f1`
prevMinute=`echo $prevDateTime | cut -d- -f4 | cut -d: -f2`
prevSecond=`echo $prevDateTime | cut -d- -f4 | cut -d: -f3`

echo "Year: $prevYear; Month: $prevMonth; Day: $prevDay"                                                                                                                                                                                                                       
echo "Hour: $prevHour; Minute: $prevMinute; Second: $prevSecond"

Upvotes: 0

chepner
chepner

Reputation: 530940

A regular expression is probably the simplest solution, given the format of prevDateTime.

[[ $prevDateTime =~ (.*)-(.*)-(.*)-(.*):(.*):(.*) ]]
prevYear=${BASH_REMATCH[1]}
prevMonth=${BASH_REMATCH[2]}
# etc.

Technically, there's a "one"-liner to do this using declare:

declare $(date +'prevDateTime=%Y-%m-%d:%H:%M:%S
prevYear=%Y
prevMonth=%m
prevDat=%d
prevHour=%H
prevMinute=%M
prevSecond=%S')

It uses date to output a block of parameter assignments which declare instantiates. (Note that the command substitution is not quoted, so that each assignment is seen as a separate argument to declare. If there was any whitespace in the values to assign, you would have to switch to using eval with slightly different output from date.)

Upvotes: 3

Related Questions