首页 > 解决方案 > Sed/Tr 对 api 输出进行排序

问题描述

我需要帮助来对 api 输出进行排序并排序并获取最新信息

{
 "name" : "xyz.abc",
 "tags" : [ "1.0.33", "1.0.35", "1.0.47", "1.0.63", "1.0.56", "1.0.45", "1.0.58", "1.0.31", "1.0.39", 
 "1.0.30", "1.0.51", "1.0.41", "1.0.46", "1.0.32", "1.0.64", "1.0.65", "1.0.67", "1.0.42", "1.0.36", 
 "1.0.37", "1.0.53", "1.0.43", "1.0.44", "1.0.48", "1.0.49" ]
}

我试过了 -

     cat test2.text | grep tags | tr -d '[|]' | sed -n '/ *"tags" *: *"/ { s///; s/".*//; p; }'`
     1.0.33

需要的输出:

      1.0.67

标签: bashshellunixsedtr

解决方案


您可以ruby像这样使用内置 JSON 库:

$ ruby -r json -e 'puts JSON.parse($<.read)["tags"]' file | sort | tail -n 1
1.0.67

或者,完全ruby没有管道:

$ ruby -r json -e 'puts JSON.parse($<.read)["tags"].sort_by{|s| s.split[-1]}[-1]' file 

或者,使用jqand sed

$ jq -c '.tags | sort' file | sed -nE 's/.*"([0-9.]*)"]$/\1/p'
1.0.67

或者只使用jq's max

$ jq -c '.tags | max' file 
"1.0.67"                     # you can remove the " with sed

这些适用于您的示例,但会因其他常用版本字符串而失败。例如,是1.0.255比 更高还是更早的版本1.0.67

如果您想进行正确的版本排序(例如,1.0.255排序比例如晚1.0.67),您可以在 Ruby 中使用:

$ ruby -r json -e 'puts JSON.parse($<.read)["tags"].sort_by{|s| Gem::Version.new(s)}[-1]' file 

许多版本的 Unixsort也支持版本排序,所以如果你想支持带有-V参数的典型版本字符串来对上面的管道进行排序。


推荐阅读