这是我写的脚本。
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
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
在此预期输出为:
2018-04-11 09:21:35,60
2018-04-11 10:45:00,900
但我得到的输出是:
2018-04-13,0921
2018-04-13,60
2018-04-13,1045
2018-04-13,900
任何人都可以纠正错误是什么吗?
答案 0 :(得分:2)
在GNU awk中:
awk '
{
split($1 " " $2,a,"[.: ]") # split for mktime
s=mktime(a[3] " " a[2] " " a[1] " " a[4] " " a[5] " " a[6]) # to secs
if($4=="end_time") # at end_time
print strftime("%Y-%m-%d %H:%M:%S,",p) s-p # print start time and difference
p=s # set secs to prev
}' file
2018-04-11 09:21:35,60
2018-04-11 10:45:00,900
答案 1 :(得分:0)
我认为这个问题应该分开多个问题。 您如何看待下面的代码?
$ 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
您可以通过增加管道命令来查看这些代码实际执行的操作,如下所示:
{{1}}