LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   no of days between two dates in yyyymmdd format (http://www.linuxquestions.org/questions/programming-9/no-of-days-between-two-dates-in-yyyymmdd-format-903694/)

csegau 09-18-2011 12:21 PM

no of days between two dates in yyyymmdd format
 
Hi All,

I have a file which has 3 column, column 2nd and 3rd have date in yyyymmdd format.

i have to find find the no. of days between two dates.


ex: file
column1 column2 column3
-----------------------------------
A 20090909 20100908
A 20080102 20090107
B 20110909 20110910
A 20001010 20030405

so i have to find out no of days when "A" was present.
this input "A" is command line argument, it can be "B" too..


-Thanks in advance

theNbomr 09-18-2011 02:15 PM

If I understand your question correctly, you want to calculate the difference between dates, in days, for records that match a specified argument. If so, this should be close:
Code:

#! /bin/bash
#
#  LQcsegau.sh
#      run as: LQcsegau.sh A    # (use record type as desired)
#      -  uses embedded data file name; customize as necessary
#
while read rec; do
    #
    #  Split each record into separate fields
    #
    rectype=$(echo $rec | cut -d' ' -f1);
    d1=$(echo $rec | cut -d' ' -f2);
    d2=$(echo $rec | cut -d' ' -f3);
 
    #
    #  If record type matches that specified on commandline...
    #
    if [ "$rectype" = "$1" ]; then
        #
        #  normalize dates to seconds-since-epoch
        #
        date1=$(date -d "$d1" "+%s" );
        date2=$(date -d "$d2" "+%s" );
       
        #
        #  Calculate difference in seconds, convert back to days, and report
        #
        days=$(( ($date2-$date1)/86400 ));
        echo $days;
    fi;
#
#  Read from data file
#
done < LQcsegau.dat

--- rod.


All times are GMT -5. The time now is 07:36 PM.