bash - 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
解决方案
您可以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
或者,使用jq
and 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
参数的典型版本字符串来对上面的管道进行排序。
推荐阅读
- python - 我想将熊猫数据转换为日期时间索引
- ruby-on-rails - 指定环境时,Webpacker 不替换“process.env”变量
- c++ - 接受用户输入并显示它的程序
- bootstrap-4 - 列与多行对齐的引导布局
- javascript - 第 (345) 行第 (62) 列的 JavaScript 解析错误问题 = 无效的属性 id (
; 第 345 行) - r - 如何在R中的df中获得前100个独特的地方?
- python - 如何在python中自动化这个重复的过程
- sql - Calculating percentage change with SQL windows analytic function
- c# - 快速单击几次后,WPF按钮部分不起作用
- python - 如何计算天数,那么天数是多少小时?