从键值日志文件创建类似表的文件

从键值日志文件创建类似表的文件

我有一个这样的日志文件

27/12/2020 00:05:30,848 ===== Request ======
code = 0
trigger1 = false
trigger2 = false
field = {
     1|status=0
     2|tag=abcdef
     3|price=35
     ...
}
===== Response =====
code = 1
trigger1 = false
trigger2 = false
field = {
     5|id=123
     1|status=404
     2|tag=ghijkl
     4|barcode=26121111
     3|price=35
     ...
}
27/12/2020 00:10:35,941 ===== Request ======
code = 0
trigger1 = false
trigger2 = false
field = {
     1|status=0
     2|tag=abcdef
     3|price=35
     ...
}
===== Response =====
code = 1
trigger1 = false
trigger2 = false
field = {
     5|id=123
     1|status=404
     2|tag=ghijkl
     4|barcode=26121111
     3|price=35
     ...
}

代表...所有不太有用的领域。我想创建一个像这样的表(或者 csv 文件也很好):

Time                     id   status tag    price barcode
27/12/2020 00:05:30,848  Null 0      abcdef 35    Null
27/12/2020 00:05:30,848  123  404    ghijkl 35    26121111
27/12/2020 00:10:35,941  Null 0      abcdef 35    Null
27/12/2020 00:10:35,941  123  404    ghijkl 35    26121111

我用过这个解决方案但效果不佳:( 现在我临时用来grep将状态、标签和价格添加paste到单个文件中,因为它具有相同数量的输出,但 id 和条形码却不是。我的代码有点像这样:

grep "1|status=" file > status
grep "2|tag=" file > tag
grep "3|price=" file > price
paste status tag price > output

我的输出文件看起来像这样

1|status=0   2|tag=abcdef  3|price=35
1|status=404 2|tag=ghijkl  3|price=35
1|status=0   2|tag=abcdef  3|price=35
1|status=404 2|tag=ghijkl  3|price=35

我想在每个中 grepfield = { * }并查看它是否具有所有键值,如果不返回 null。我对 bash 脚本非常陌生,所以我真的不知道我解决它的方法是否是优化的。我需要你们的帮助。谢谢你!!!

答案1

$ cat tst.awk
BEGIN {
    OFS = "\t"
    numTags = split("Time id status tag price barcode",tags)
    for (tagNr=1; tagNr<=numTags; tagNr++) {
        tag = tags[tagNr]
        printf "%s%s", tag, (tagNr<numTags ? OFS : ORS)
    }
}
/= Request =/ {
    time = substr($0,1,23)
}
sub(/^[[:space:]]*([0-9]+\|)?/,"") {
    tag = val = $0
    sub(/[[:space:]]*=.*/,"",tag)
    sub(/[^=]+=[[:space:]]*/,"",val)
    tag2val[tag] = val
}
/^}/ {
    tag2val["Time"] = time
    for (tagNr=1; tagNr<=numTags; tagNr++) {
        tag = tags[tagNr]
        val = (tag in tag2val ? tag2val[tag] : "Null")
        printf "%s%s", val, (tagNr<numTags ? OFS : ORS)
    }
    delete tag2val
}

$ awk -f tst.awk file | column -s$'\t' -t
Time                     id    status  tag     price  barcode
27/12/2020 00:05:30,848  Null  0       abcdef  35     Null
27/12/2020 00:05:30,848  123   404     ghijkl  35     26121111
27/12/2020 00:10:35,941  Null  0       abcdef  35     Null
27/12/2020 00:10:35,941  123   404     ghijkl  35     26121111

相关内容