Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

Date problem

  • 08-09-2005 03:52PM
    #1
    Closed Accounts Posts: 1


    I have a requirement to echo a date range from the unix command line.
    My requirement is as follows:

    Start_date=20050901
    end_date= 20050907

    What I want to do is start from "start_date" and echo a filename "filexyz_20050901", "filexyz20050902"..... "filexyz_20050907"

    so effectively in this example, I would want to do 7 echo commands...

    Is it possible to do this in one unix command, or do I need a script?

    Many thanks in anticipation

    Richie


Comments

  • Closed Accounts Posts: 95 ✭✭krinDar


    Great big durty hack number one that will work in bash and ksh:
     i=$Start_date 
    
    while (( i <= end_date )); do echo "filexyz_${i}"; i=$((i + 1)); done
    

    This doesn't handle a month roll over however...


  • Closed Accounts Posts: 95 ✭✭krinDar


    krinDar wrote:

    This doesn't handle a month roll over however...

    This one does ... And year roll over, and isn't bothered by leap years...
    #!/bin/bash
    
    SD_year=${1:0:4}
    SD_month=$((10#${1:4:2}))
    SD_day=$((10#${1:6:2}))
    
    ED_year=${2:0:4}
    ED_month=$((10#${2:4:2}))
    ED_day=$((10#${2:6:2}))
    
    while (( SD_year < ED_year || 
            (SD_year == ED_year && SD_month < ED_month) || 
            SD_year == ED_year && SD_month == ED_month && SD_day <= ED_day ))
    do
            printf "filexyz_%4.4d%2.2d%2.2d\n" ${SD_year} ${SD_month} ${SD_day}
    
            # Get days in month
            ndim=$(cal $SD_month $SD_year | awk '/^[0-9]+/{line=$NF}END{print line}')
    
            # If at the end of the month, increment, if at month twelve, 
            # increment year
            if (( SD_day == ndim))
            then
                    if (( SD_month == 12 ))
                    then
                            SD_month=1;
                            SD_year=$((SD_year+1))
                    else
                            SD_month=$(( SD_month+1))
                    fi
                    SD_day=1;
            else
                    SD_day=$(( SD_day+1))
            fi
    done
    
    

    Stick it into a file, set the permissions to executeable and run it as follows
    assuming you put it into a file called script.sh:
    $ ./script.sh 20050901 20050904
    filexyz_20050901
    filexyz_20050902
    filexyz_20050903
    filexyz_20050904
    

    This requires bash, at least version 2.05.


Advertisement