Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash shell date parsing, start with specific date and loop through each day in month

I need to create a bash shell script starting with a day and then loop through each subsequent day formatting that output as %Y_%m_d

I figure I can submit a start day and then another param for the number of days.

My issue/question is how to set a DATE (that is not now) and then add a day.

so my input would be 2010_04_01 6

my output would be

2010_04_01
2010_04_02
2010_04_03
2010_04_04
2010_04_05
2010_04_06
like image 391
Joe Stein Avatar asked Apr 16 '10 20:04

Joe Stein


People also ask

What does =~ mean in bash?

A regular expression matching sign, the =~ operator, is used to identify regular expressions. Perl has a similar operator for regular expression corresponding, which stimulated this operator.

What is $() in bash script?

$() Command Substitution According to the official GNU Bash Reference manual: “Command substitution allows the output of a command to replace the command itself.


5 Answers

[radical@home ~]$ cat a.sh 
#!/bin/bash

START=`echo $1 | tr -d _`;

for (( c=0; c<$2; c++ ))
do
    echo -n "`date --date="$START +$c day" +%Y_%m_%d` ";
done

Now if you call this script with your params it will return what you wanted:

[radical@home ~]$ ./a.sh 2010_04_01 6
2010_04_01 2010_04_02 2010_04_03 2010_04_04 2010_04_05 2010_04_06
like image 114
eRadical Avatar answered Oct 04 '22 15:10

eRadical


Note: NONE of the solutions here will work with OS X. You would need, for example, something like this:

date -v-1d +%Y%m%d

That would print out yesterday for you. Or with underscores of course:

date -v-1d +%Y_%m_%d

So taking that into account, you should be able to adjust some of the loops in these examples with this command instead. -v option will easily allow you to add or subtract days, minutes, seconds, years, months, etc. -v+24d would add 24 days. and so on.

like image 37
Tom Avatar answered Oct 04 '22 16:10

Tom


Very basic bash script should be able to do this.

Script:
#!/bin/bash

start_date=20100501
num_days=5
for i in seq 1 $num_days
do
    date=date +%Y/%m/%d -d "${start_date}-${i} days"
    echo $date # Use this however you want!
done

Output:
2010/04/30
2010/04/29
2010/04/28
2010/04/27
2010/04/26

like image 33
anonymous Avatar answered Oct 04 '22 15:10

anonymous


#!/bin/bash
inputdate="${1//_/-}"  # change underscores into dashes
for ((i=0; i<$2; i++))
do
    date -d "$inputdate + $i day" "+%Y_%m_%d"
done
like image 30
Dennis Williamson Avatar answered Oct 04 '22 16:10

Dennis Williamson


You can also use cal, for example

YYYY=2014; MM=02; for d in $(cal $MM $YYYY | grep "^ *[0-9]"); do DD=$(printf "%02d" $d); echo $YYYY$MM$DD; done

(originally posted here on my commandlinefu account)

like image 42
Gianluca Casati Avatar answered Oct 04 '22 16:10

Gianluca Casati