0

I have a date in the variable x=20170402, getting this value from another file.
I want to modify this by adding/subtracting and save to new variable. How can i do this?
ex: if i subtract one day, y=20170401; two days, y=20170331
and it is GNU based.

Cyrus
  • 84,225
  • 14
  • 89
  • 153
user491
  • 175
  • 1
  • 4
  • 20
  • do you have `GNU date`? or `FreeBSD` one? output `date --version`? – Inian Apr 03 '17 at 05:36
  • 1
    Also can you provide an exact output you need for your input? This information is not sufficient – Inian Apr 03 '17 at 05:37
  • 1
    Possible duplicate of [How to increment a date in a bash script](https://stackoverflow.com/q/18706823/608639) – jww Sep 20 '18 at 02:01

3 Answers3

4

With GNU date it can be done quite easily with its -d switch.

x=20170402
date -d "$x -1 days" "+%Y%m%d"
20170401

and for 2 days

date -d "$x - 2 days" "+%Y%m%d"
20170331
Inian
  • 80,270
  • 14
  • 142
  • 161
3

The command date should be enough.

$ x=20170402;
$ date -d "$x 1 day ago" +'%Y%m%d'
20170401

$ date -d "$x 2 day ago" +'%Y%m%d'
20170331
0

-d flag for this would serve the purpose. $Number is the number of days you wish to substract.

x=20170402
past_date=$(date -d "$x - $Number days" +%Y%m%d)
echo "$past_date"
Ashish K
  • 905
  • 10
  • 27