这是我写的剧本。
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
有人能纠正什么是错误吗?
最佳答案
我认为这个问题应该分为多个问题。
你觉得下面的代码怎么样?
# 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)
}'
您可以通过递增管道命令来查看这些代码实际执行的操作,如下所示:
$ 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
关于linux - 在同一行中打印awk的两个匹配变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49808754/