Assigning a value to a variable

Hi

I have a script that accepts an input date in YYYY-MM-DD format.

After that, I used sed to delete the hyphen (-) which gives me an output YYYY MM DD.

My question is, how can I assign those three numbers to a three different variable.

Example:

2013-11-23 will become 2013 11 23

I want to assign that three to a variable individually like this;
$X=2013
$Y=11
$Z=23

Thanks.

#! /bin/bash

OLDIFS=$IFS
IFS='-'

read x y z
echo "$x $y $z"

IFS=$OLDIFS
1 Like

If you are not replacing - with space then the below will work.

x=$(echo $1|cut -d'-' -f1)
y=$(echo $1|cut -d'-' -f2)
z=$(echo $1|cut -d'-' -f3)
1 Like

If you're using sed to get rid of the minus signs, the date string must be in a file. Try:

IFS='-' read X Y Z < date_file
printf '$X=%s\n$Y=%s\n$Z=%s\n' "$X" "$Y" "$Z"

Note that you don't need to save and restore the value of IFS if you just set its value to be other than the default only for the call to read.

2 Likes

another question, how can I make sure that the month and day variable will have fixed two digit value.

Example:

Y=2013
M=3
D=9

How can I change those(M=3, D=9) to two digit (03, 09) and be sure that when the input is for example M=11, D=23 the output won't be M=011 and D=023

Thanks.

---------- Post updated at 09:25 PM ---------- Previous update was at 08:59 PM ----------

actually, don't mind this, I already got it. Thanks again nice people!