Naveen
Naveen

Reputation: 1

Shell Date conversion and assign to Variable

I have requirement like convert a string date to below format and assign to variable for futher processing.

    Input is string as below
    str = 20210709
    Need to get yesterday date and change the format to %Y-%m-%d
    (date -d 'str -1 days' +'%Y-%m-%d')
    and i am expecting output in a variable like below
    dt = 2021-06-09

    I tried like below
    dt =  date -d '20210709 -1 days' +'%Y-%m-%d'
    and the error as below
    -bash: d: command not found

Any ideas/Suggestions would be greatly appreciated.

Upvotes: 0

Views: 634

Answers (2)

glenn jackman
glenn jackman

Reputation: 246744

You're missing a couple of things:

str=20210709
dt=$(date -d "$str - 1 day" '+%F')
echo "$dt"
2021-07-08

Upvotes: 1

Kyle Banerjee
Kyle Banerjee

Reputation: 2784

dt=$(paste -d "-" <(echo $str |cut -c1-4) <(echo $str |cut -c5-6) <(echo $str |cut -c7-8))

If your version of linux doesn't like that syntax, then

dt=$(sed 's/\(....\)\(..\)\(..\)/\1-\2-\3/' <<< $str)

Upvotes: 0

Related Questions