Hi Experts,
In the below mentioned file,
John, Miami, ,2013-10-03
I would like to perform difference of $4 and sysdate.
If sysdate date is 2013-10-04, then the output shall be
John, Miami,,1
For which I tried something like the one shown below,
#!/bin/bash
sed -e "s/-//g" file > tmp
t=`date "+%Y%m%d"`
awk -F',' '{s=$(date -d"$4" +%s); j=$(date -d"$t" +%s); k=$($($($j-$s)/3600)/24); print $1","$2","$3","k}' input > output
Can someone please tweak the awk expression and make it to work.
I wanted to return 1380747600 for s and 1380834000 for j.
So that j-s=86400
convert into days ->(j-s)/3600/24
The date expressions work fine in bash, but not in awk.
-Victor
awk does not work that way, $ does not work that way, $( ) does not work that way, date does not work that way, and you cannot use shell expressions inside awk that way.
What version of awk do you have? If you have GNU awk you have some date functions built in.
awk -F, -v OFS="," '{ split(/-/, A, $3); T=systime()-mktime(sprintf("%04d %02d %02d 00 00 00", A[1], A[2], A[3]));
T/=(60*60*24);
$3=T;
} 1' inputfile
Thanks Corona for the reply.
As I was having the date in $4, I changed as follows.
gawk -F, -v OFS=, '{ split(/-/, A, $4); T=systime()-mktime(sprintf("%04d %02d %02d 00 00 00", A[1], A[2], A[3]));
T/=(60*60*24);
$4=T;
} 1' inputfile
$ cat inputfile
John,Miami,,2013-10-03
$ date
Fri Oct 4 23:17:36 AST 2013
$ bash -x scr.sh
+ gawk -F, -v OFS=, '{ split(/-/, A, $4); T=systime()-mktime(sprintf("%04d %02d %02d 00 00 00", A[1], A[2], A[3]));
T/=(60*60*24);
$4=T;
} 1' inputfile
John,Miami,,735177
Kindly help, as it is not giving the expected result.
I changed to gawk, as I'm running on Linux.
I mixed up the array and the split string in split(), try this:
gawk -F, -v OFS=, '{ split($4, A, "-"); T=mktime(sprintf("%04d %02d %02d 00 00 00", A[1], A[2], A[3]));
$4=int((systime()-T)/(60*60*24));
} 1' inputfile
1 Like
corona688:
I mixed up the array and the split string in split(), try this:
gawk -F, -v OFS=, '{ split($4, A, "-"); T=mktime(sprintf("%04d %02d %02d 00 00 00", A[1], A[2], A[3]));
$4=int((systime()-T)/(60*60*24));
} 1' inputfile
Thanks for the change, it worked as expected . This gave me an opportunity to get an insight on awk programming.
1 Like