2016-08-12 68 views
0

我试图从我的Elasticache中使用AWS CLI获取最新(最高号码前缀)CacheClusterId,以便将其放入Chef配方中。这是我到目前为止有:Bash在排序后解析JSON名称

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” 部分(减去引号)?阅读手册页进行排序,我觉得它需要一个-k选项,但我无法解决详细情况。

回答

0

由于第一部分的都是一样,我将只是削减,并采取ID参与方式如下:

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

有趣。我是否也可以使用剪切来抓取最高记录?这是我感兴趣的唯一一个。现在,我的输出与上面(多条记录)相同,但没有CacheClusterId部分和引号。 –

+1

如果它始终是最高记录,您可以将结果剪切到'head -n 1' – Fma

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" , ... }, 
    ... 
    ] 
} 

那么你“d写:

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

对于上面的阵列中的两个JSON对象,它会返回:

"xy112-elasticache" 
"xy111-elasticache" 
+0

感谢您的回答。总而言之,我需要在Chef中运行这个命令来懒惰地评估我创建的所有框,并且我不愿添加其他依赖项,因此选择了bash路由。不过,我会记住这一点,以便将来进行分类。它看起来非常强大。 –

+0

@Rome_Leader没有任何借口,使用它! – hek2mgl

+0

@Rome_Leader它非常强大!处理JSON比使用'sed'或任何流编辑器更好的方法;我相信你知道着名的“用正则表达式解析HTML”这个问题,我认为类似地使用流编辑器来解析数据语言。 –