2

This is my JSON output for this command aws logs list-log-groups and from this I need the first "arn" value to be grepped. How can I do this?

{
    "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
        }
    ]
}
ahmedg
  • 247

2 Answers2

3

I've recently discovered a tool called 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;

This tool transforms the JSON notation into line-by-line javascript that is easily greppable.

$ 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:*:*
glenn jackman
  • 17,900
2

Use jq:

aws logs list-log-groups | jq -r '.logGroups[0].arn'

Output:

arn:aws:logs:us-east-1:929815623526:log-group:alla:

jq can be installed from the universe repository:

sudo apt install jq

jq is to be preferred for parsing json, but if jq is no option for whatever reason and you know that the format won't change, you can possibly use grep -P and head -n1:

aws logs list-log-groups | grep -Po '"arn": "\K[^"]*' | head -n1
pLumo
  • 26,947