This is the script which i wrote.
Date=$(date +'%Y-%m-%d') for i in `awk -F"[.: ]" '/start/{start=($4 * 3600) + ($5 * 60) + $6;date=$4$5} /end/{print date;print (($4 * 3600) + ($5 * 60) + $6)-start;start=""}' logs.txt`; do echo "$i" done
The logs.txt consists of :
11.04.2018 09:21:35 aaaaa: start_time 11.04.2018 09:22:35 aaaaa: end_time 11.04.2018 10:45:00 aaaaa: start_time 11.04.2018 11:00:00 aaaaa: end_time
In this the expected output is :
2018-04-11 09:21:35,60 2018-04-11 10:45:00,900
But the output i am getting is :
2018-04-13,0921 2018-04-13,60 2018-04-13,1045 2018-04-13,900
Can anyone rectify what is the error ?
Advertisement
Answer
I thinks this problem should be separated multiple problems. How do you think about below code?
# extract records: log file may contain other informations awk '$4=="start_time";$4=="end_time"' logs.txt | # wrap records: # # start_time and end_time may appear alternately in the log. # # wrap a pair into 1 line. awk '{if(NR%2==1){ printf("%s ",$0) }else{ print }}' | # and convert # # tr command character wise editor, read ``man tr''. tr '.:' ' ' | # # make your favorite output awk -v OFS="," '{ print $3 "-" $2 "-" $1 " " $4 ":" $5 ":" $6, 3600 * ($12-$4) + 60 * ($13-$5) + ($14-$6) }'
You can see what these code actually do by increment piped commands, as shown below:
$ awk '$4=="start_time";$4=="end_time"' logs.txt 11.04.2018 09:21:35 aaaaa: start_time 11.04.2018 09:22:35 aaaaa: end_time 11.04.2018 10:45:00 aaaaa: start_time 11.04.2018 11:00:00 aaaaa: end_time $ awk '$4=="start_time";$4=="end_time"' logs.txt | > awk '{if(NR%2==1){ printf("%s ",$0) }else{ print }}' 11.04.2018 09:21:35 aaaaa: start_time 11.04.2018 09:22:35 aaaaa: end_time 11.04.2018 10:45:00 aaaaa: start_time 11.04.2018 11:00:00 aaaaa: end_time $ awk '$4=="start_time";$4=="end_time"' logs.txt | > awk '{if(NR%2==1){ printf("%s ",$0) }else{ print }}' | > tr '.:' ' ' 11 04 2018 09 21 35 aaaaa start_time 11 04 2018 09 22 35 aaaaa end_time 11 04 2018 10 45 00 aaaaa start_time 11 04 2018 11 00 00 aaaaa end_time $ awk '$4=="start_time";$4=="end_time"' logs.txt | > awk '{if(NR%2==1){ printf("%s ",$0) }else{ print }}' | > tr '.:' ' ' | > awk -v OFS="," '{ > print $3 "-" $2 "-" $1 " " $4 ":" $5 ":" $6, > 3600 * ($12-$4) + 60 * ($13-$5) + ($14-$6) > }' 2018-04-11 09:21:35,60 2018-04-11 10:45:00,900