我有一些以类似 JSON 的格式存储的数据。
{
{
value1: 14,
value2: 12,
value3: 1
},
{
value1: 4,
value3: -1
}
}
如何使用awk
(我认为这是最可取的并且与此类问题相关的)sed
或 来获得具有最大“value3”值的小节grep
?
所以,这个输出是预期的:
{
value1: 14,
value2: 12,
value3: 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