Bash在排序后解析JSON名称

时间:2016-08-12 14:36:44

标签: json bash

我正在尝试使用AWS CLI从我的Elasticache获取最新(最高编号前缀)CacheClusterId,以便将其放入Chef配方中。这是我到目前为止所得到的:

aws elasticache describe-cache-clusters --region us-east-1 | grep CacheClusterId | sort -t : -rn

产生:

"CacheClusterId": "xy112-elasticache"
"CacheClusterId": "xy111-elasticache"
"CacheClusterId": "xy110-elasticache"
"CacheClusterId": "xy109-elasticache"
"CacheClusterId": "xy-elasticache"

如何只隔离“xy112-elasticache”部分(减去引号)?阅读了man页面进行排序后,我觉得它需要一个-k选项,但我无法弄清楚这些细节。

2 个答案:

答案 0 :(得分:1)

我认为更好的方法是使用jq处理JSON。要在Debian上安装:

sudo apt-get install jq

我不确切知道您的JSON是什么样的,但基于aws elasticache describe-cache-clusters命令的this XML example响应,如果您的JSON响应如下:

{ 
  "CacheClusters": [
    { "CacheClusterId": "xy112-elasticache" , ... },
    { "CacheClusterId": "xy111-elasticache" , ... },
    ...
  ]
}

然后你写了:

aws elasticache describe-cache-clusters --region us-east-1 | jq ".CacheClusters[].CacheClusterId"

对于上面数组中的两个JSON对象,它将返回:

"xy112-elasticache"
"xy111-elasticache"

答案 1 :(得分:0)

由于第一部分对所有部分都是相同的,所以我将剪切它们并按照以下方式获取id部分:

aws elasticache describe-cache-clusters --region us-east-1 | grep CacheClusterId | cut -d'"' -f4