获取具有最大元素的数据部分

ДМИ*_*КОВ 2 grep sed awk

我有一些以类似 JSON 的格式存储的数据。

{
    {
        value1: 14,
        value2: 12,
        value3: 1
    },
    {
        value1: 4,
        value3: -1
    }
}
Run Code Online (Sandbox Code Playgroud)

如何使用awk(我认为这是最可取的并且与此类问题相关)获得具有最大“value3”值的小节,sed或者grep

所以,这个输出是期望的:

{
    value1: 14,
    value2: 12,
    value3: 1
}
Run Code Online (Sandbox Code Playgroud)

man*_*ork 6

假设格式始终如示例中所示 - 每行一个值或节分隔符:

awk '/\{/{s="";i=1}i{s=s"\n"$0}$1=="value3:"{v=$2}/\}/{if(V==""||V<v){V=v;S=s}i=0}END{print S}' json-like.file
Run Code Online (Sandbox Code Playgroud)

一个RS基于的替代方案,如果没有得到节分隔符是可以接受的:

awk -vRS='}' '{sub(/.*\{/,"")}match($0,/value3: (\S+)/,m)&&(v==""||v<m[1]){v=m[1];s=$0}END{print s}' json-like.file
Run Code Online (Sandbox Code Playgroud)

一种RT基于替代:

awk -vRS='\\{[^{}]+\\}' 'match(RT,/value3: (\S+)/,m)&&(v==""||v<m[1]){v=m[1];s=RT}END{print s}' json-like.file
Run Code Online (Sandbox Code Playgroud)

评论中要求的解释

awk '
/\{/{s="";i=1}   # start of section? reset accumulated section data; set inside section flag
i{s=s"\n"$0}   # inside section? append current record to the accumulated data
$1=="value3:"{v=$2}   # value3 entry? store its value
/\}/{if(V==""||V<v){V=v;S=s}i=0}   # end of section? if no previous max or previous max value less than current value then set maxvalue to value and max section to section; reset inside section flag
END{print S}   # output max section
' json-like.file

awk -vRS='}' '   # record separator is the end of section delimiter
{sub(/.*\{/,"")}   # remove start of section delimiter and anything before it
match($0,/value3: (\S+)/,m)&&(v==""||v<m[1]){v=m[1];s=$0}   # current record contains value3 entry and no previous max or previous max value is less than its value? set max value to value and section to current record
END{print s}   # output section
' json-like.file

awk -vRS='\\{[^{}]+\\}' '   # record separator is an entire section
match(RT,/value3: (\S+)/,m)&&(v==""||v<m[1]){v=m[1];s=RT}   # current record terminator contains value3 entry and no previous max or previous max value is less than its value? set max value to value and section to current record terminator
END{print s}   # output section
' json-like.file
Run Code Online (Sandbox Code Playgroud)