最大の要素を含むデータ部分を取得する

最大の要素を含むデータ部分を取得する

JSONなどの形式で保存されたデータがいくつかあります。

{
    {
        value1: 14,
        value2: 12,
        value3: 1
    },
    {
        value1: 4,
        value3: -1
    }
}

awk(私の考えでは、これがこの種の問題に最も望ましいと関連していると思います)、またはを使用してsed最大「value3」値を持つサブセクションをどのように取得できますかgrep

したがって、次の出力が予想されます。

{
    value1: 14,
    value2: 12,
    value3: 1
}

ベストアンサー1

フォーマットが常に例に示されているのと同じであると仮定します。つまり、1行に1つの値またはセクション区切り文字があります。

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

RSセクション区切り文字がない場合 - ベースの代替が許可されます。

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

- ベースの代替RT:

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

説明するコメントでリクエストしたとおり。

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

おすすめ記事