如何找到第一次匹配的记录并稍后与 awk 一起使用
Posted
技术标签:
【中文标题】如何找到第一次匹配的记录并稍后与 awk 一起使用【英文标题】:How do I find record of first match and use it later with awk 【发布时间】:2021-10-31 01:16:18 【问题描述】:假设有以下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
现在我想以通用方式查找并保存time>11
所在的第一行的记录号和内容,知道时间值在整个文件中定期记录,但不知道第一次出现在哪里的任何细节.
我尝试了以下 awk 脚本
awk '
/Time is now/ && $4+0>11 firstrecord=NR; exit
END print "First occurrence found on line: " firstrecord, $0
'
这当然可行,但问题是我需要处理整个文件。我不能在第一次出现时退出。理想情况下,我需要的脚本类似于以下伪代码:
awk '
BEGIN totalcats=0; totaldogs=0
/Time is now/ && $4+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
'
【问题讨论】:
【参考方案1】:您可以检查您的变量firstrecord
以确保该块只运行一次:
awk '
BEGIN totalcats=0; totaldogs=0
!firstrecord && /Time is now/ && $4+0>11 firstrecord=NR; rec=$0
/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
【讨论】:
以上是关于如何找到第一次匹配的记录并稍后与 awk 一起使用的主要内容,如果未能解决你的问题,请参考以下文章
如何将 Amazon Route 53 与 Digital Ocean 水滴一起使用?
Bash - Linux - 在一行中找到匹配并打印到SED / Awk / Grep行的末尾