我如何找到第一场比赛的记录并稍后与awk一起使用

How do I find record of first match and use it later with awk

假设以下 time.log 个条目

Time is now 11 and the weather is windy
Time is now 12 and the weather is nice and there are 2 cats
New animals observed 8 dogs
Time is now 13 and the weather is cold
Time is now 14 and the weather is nice
...
Time is now 10 and the weather is cold on the next morning 
New animals observed 4 cats
Time is now 11 and the weather is warm

现在我想以通用的方式查找并保存第一行where time>11的记录号和内容,知道时间值在整个文件中是周期性记录的,但不知道在哪里的任何细节第一次出现是。

我尝试使用以下 awk 脚本

awk '
  /Time is now/ && +0>11 {firstrecord=NR; exit}
  END {print "First occurrence found on line: " firstrecord, [=11=]}
 '

这当然可行,但问题是我需要处理整个文件。我不能在第一次出现时就退出。理想情况下,我需要的脚本类似于以下伪代码:

awk '
  BEGIN {totalcats=0; totaldogs=0}
  /Time is now/ && +0>11 {firstrecord=NR}
  /searchpattern for cats/ {totalcats+=cats_counted_in_this_record}
  /searchpattern for dogs/ {totaldogs+=dogs_counted_in_this_record}
  END {
    printf "We found a total of %d cats and %d dogs in this log.", totalcats, totaldogs;
    print "First occurrence was found on line: " firstrecord, $firstrecord_content}
 '

您可以检查您的变量 firstrecord 以确保块 运行 只有一次:

awk '
  BEGIN {totalcats=0; totaldogs=0}
  !firstrecord && /Time is now/ && +0>11 {firstrecord=NR; rec=[=10=]}
  /searchpattern for cats/ {totalcats+=cats_counted_in_this_record}
  /searchpattern for dogs/ {totaldogs+=dogs_counted_in_this_record}
  END {
    printf "We found a total of %d cats and %d dogs in this log.\n", totalcats, totaldogs
    print "First occurrence was found on line: " firstrecord, rec}
 ' file