这是此命令的 JSON 输出aws logs list-log-groups
,我需要从中获取第一个“arn”值。我该怎么做?
{
"logGroups": [
{
"logGroupName": "alla",
"creationTime": 1594638588652,
"metricFilterCount": 0,
"arn": "arn:aws:logs:us-east-1:12345678910:log-group:*:*",
"storedBytes": 0
},
{
"logGroupName": "mahi",
"creationTime": 1594638580461,
"metricFilterCount": 0,
"arn": "arn:aws:logs:us-east-1:12345678910:log-group:*:*",
"storedBytes": 0
}
]
}
答案1
我最近发现了一个工具叫gron
。
gron <<'END_JSON'
{
"logGroups": [
{
"logGroupName": "alla",
"creationTime": 1594638588652,
"metricFilterCount": 0,
"arn": "arn:aws:logs:us-east-1:12345678910:log-group:*:*",
"storedBytes": 0
},
{
"logGroupName": "mahi",
"creationTime": 1594638580461,
"metricFilterCount": 0,
"arn": "arn:aws:logs:us-east-1:12345678910:log-group:*:*",
"storedBytes": 0
}
]
}
END_JSON
json = {};
json.logGroups = [];
json.logGroups[0] = {};
json.logGroups[0].arn = "arn:aws:logs:us-east-1:12345678910:log-group:*:*";
json.logGroups[0].creationTime = 1594638588652;
json.logGroups[0].logGroupName = "alla";
json.logGroups[0].metricFilterCount = 0;
json.logGroups[0].storedBytes = 0;
json.logGroups[1] = {};
json.logGroups[1].arn = "arn:aws:logs:us-east-1:12345678910:log-group:*:*";
json.logGroups[1].creationTime = 1594638580461;
json.logGroups[1].logGroupName = "mahi";
json.logGroups[1].metricFilterCount = 0;
json.logGroups[1].storedBytes = 0;
此工具将 JSON 符号逐行转换为易于检索的 javascript。
$ arn=$(gron <<'END_JSON' | sed -En '/json\.logGroups\[0\]\.arn/ s/^[^"]*"(.*)";$/\1/p'
{
...
}
END_JSON
)
$ echo "$arn"
arn:aws:logs:us-east-1:12345678910:log-group:*:*
答案2
使用jq
:
aws logs list-log-groups | jq -r '.logGroups[0].arn'
输出:
arn:aws:logs:us-east-1:929815623526:log-group:alla:
jq
可以从universe
存储库:
sudo apt install jq
jq
是解析的首选json
,但如果jq
出于某种原因没有选择,并且您知道格式不会改变,您可以使用grep -P
和head -n1
:
aws logs list-log-groups | grep -Po '"arn": "\K[^"]*' | head -n1