awk 程序将文件名作为参数并处理采用该文件每一行的命令

Awk program to take file name as argument and process commands taking each line of that file

我有一个包含对象信息的日志文件。我需要 AWK

中的脚本

我的日志会是这样的:

ObjectA copy time 2ms
ObjectA ID is 23467sdfs3453AAAA
ObjectB copy time 7ms
Objectc run time 23ms
ObjectA process time 3ms
ObjectA run time 1ms
Objectc copy time 71ms
ObjectB ID is sada67AsdfsdfAA345
ObjectB process time 9ms
Objectc process time 29ms
ObjectB run time 4ms 
ObjectC ID is 534267AsdfsdfAA233

...

我的输出应该是

Objectname  |  Object ID          |    CopyTime |    RunTime |  ProcessTime
----------------------------------------------------------------------------
ObjectA     |  23467sdfs3453AAAA   |    2ms       |    1ms      | 3ms
----------------------------------------------------------------------------
ObjectB     |  sada67AsdfsdfAA345  |    7ms       |    4ms      | 9ms
----------------------------------------------------------------------------
ObjectC     |  534267AsdfsdfAA233  |    71ms      |    23ms     | 29ms 
---------------------------------------------------------------------------

这是完整的要求。 一种表格格式。

我会使用 greptr 作为列表的预处理器:

tr ',' '\n' < objects.txt | grep -Ff- logfile

tr 命令将对象文件从逗号分隔的文件转换为模式在单独一行上的文件:

ObjectA
ObjectB
ObjectC

grep -f- 使用此文件作为搜索模式列表。请注意,- 是文件名的特殊值,表示标准输入。 -F 将模式视为文字字符串而不是正则表达式。

以下 awk 脚本将解析给定的文件并使用输入的第一列键入的关联数组存储每个对象的相关信息。最后,它创建了一个简单的 table.

#!/usr/bin/awk -f

 == "copy" {
    copy_time[] = $NF;
}

 == "ID" {
    id[] = $NF;
}

 == "run" {
    run_time[] = $NF;
}

 == "process" {
    process_time[] = $NF;
}

END {
    fmt = "%-15s| %-20s | %-10s | %-10s | %-10s\n";
    div = "------------------------------------------------------------------------------";

    printf(fmt, "Object Name", "Object ID", "Copy Time",
           "Run Time", "Process Time");
    print(div);

    for (obj in id) {
        printf(fmt, obj, id[obj], copy_time[obj],
               run_time[obj], process_time[obj]);
        print(div);
    }
}

运行 它(更正了 ObjectC 的大写):

$ ./script.awk data.in
Object Name    | Object ID            | Copy Time  | Run Time   | Process Time
------------------------------------------------------------------------------
ObjectA        | 23467sdfs3453AAAA    | 2ms        | 1ms        | 3ms
------------------------------------------------------------------------------
ObjectB        | sada67AsdfsdfAA345   | 7ms        | 4ms        | 9ms
------------------------------------------------------------------------------
ObjectC        | 534267AsdfsdfAA233   | 71ms       | 23ms       | 29ms
------------------------------------------------------------------------------