【问题标题】:Awk efficiently print a matching line from a matching paragraphawk 从匹配的段落中有效地打印匹配的行
【发布时间】:2012-07-10 04:49:04
【问题描述】:

我想编写一个高效的 awk 脚本,该脚本将获取一个类似于下面显示的摘录的文件,并从每个匹配的记录中打印出某一行(例如,以“时间(UTC):”开头的行)。我相信有比我过去所做的更好的方法来做到这一点。

示例文件(对不起,我不知道如何在代码框中放置空行。它们用“BLANK LINE”表示):

Processor: Some_Proc
Capsule abortion no 32
Time (UTC): Fri Jun 15 06:25:10 2012
CapsuleId: 1704167
CapsuleName: SomeAppProc
Reason: Assertion "Reason1"  
BLANK LINE
Processor: Some_Proc
Capsule abortion no 33
Time (UTC): Fri Jun 15 06:25:10 2012
CapsuleId: 1704168
CapsuleName: SomeAppProc
Reason: Assertion "Reason2"  
BLANK LINE
Processor: Some_Proc
Capsule abortion no 34
Time (UTC): Fri Jun 15 06:25:10 2012
CapsuleId: 1704168
CapsuleName: SomeAppProc
Reason: Assertion "Reason1"

以前的代码示例(对不起,我不知道如何在这个论坛中保留缩进我尝试了 8 个空格,但没有奏效)

BEGIN {
    RS=""  #Each record is a "paragraph"
    FS="\n" #Each field is a line
}

/Reason1/ {
    # print $3  would work if it always shows up on the third line
    # but the following for loop should find it if it's on a different line
    for (i=1;i<=NF;i++) {
        if ($i ~ /^Time.*/) {
            print $i
            next
        }
    }
} 

如果行不总是以相同的顺序出现,是否有更有效的方法来打印行?

谢谢

【问题讨论】:

    标签: printing awk line match paragraph


    【解决方案1】:

    这对我来说似乎是一个很好的解决方案。我会使用相同的方法来解决这个问题。我会使用break 而不是next,因为您想在找到该行后停止循环。 next 指令没有什么意义,因为它执行循环的下一个循环,如果它不存在则相同。

    for (i=1;i<=NF;i++) {
        if ($i ~ /^Time.*/) {
            print $i
            break
        }
    }
    

    【讨论】:

    • 我没有尝试过代码,但是我尝试使用将停止处理当前记录并继续下一条记录的命令。
    【解决方案2】:

    这样的事情怎么样?:

    BEGIN { reset(); }
    END { reset(); }
    $0 == "" { reset(); }
    /^Reason:/ && $3 == "\"Reason1\"" { found = 1; }
    /^Time \(UTC\):/ { time = $0; }
    
    function reset() {
      if (found) { print time; }
      found = 0;
      time = "(unknown)";
    }
    

    然后只使用默认的换行符记录分隔符。它的作用是在读取时间和原因字段时记下它们,然后在每个匹配记录的末尾打印出时间。

    【讨论】:

      猜你喜欢
      • 2011-06-20
      • 1970-01-01
      • 2020-06-05
      • 2014-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-04
      • 1970-01-01
      相关资源
      最近更新 更多