-   Linux - Newbie (
-   -   How to subtract two dates in a file to get number of days? (

btacuso 07-04-2010 05:35 PM

How to subtract two dates in a file to get number of days?
I have a sample file with six fields delimited by commas below:

1astname1,firsname1 , 216057926,102,07/03/10,07/04/10
lastname2,firstname2 , 211968262,105,07/01/10,07/04/10
lastname3,firstname3, 214783220,113,06/29/10,07/04/10

field 5 is first date
field 6 is last date

I need to subtract field6 - field5 to get the number of days and then append it as field7 to the file. Desired result is below:

1astname1,firsname1 , 216057926,102,07/03/10,07/04/10,1
lastname2,firstname2 , 211968262,105,07/01/10,07/04/10,3
lastname3,firstname3, 214783220,113,06/29/10,07/04/10,5

I appreciate any help.

colucix 07-04-2010 06:04 PM

You can simply use the date command and the bash arithmetic operator. Date differences are usually made in seconds since epoch units, then we can apply any conversion to days, hours and so on by means of the proper conversion factor. Since you don't need fractional parts of the day, bash (integer) arithmetic is enough. An example of the date command:

$ my_date="07/04/10"
$ date -ud $my_date +%s

Note the -u option to work with UTC time. It's useful if by chance the two dates span across the day of change from/to Daylight Saving Time.

btacuso 07-13-2010 11:33 AM

Thanks a lot. I was able to fix it thru this guide.

All times are GMT -5. The time now is 03:50 PM.