文本处理中 - 在命令行中,如何grep JSON key的值?

分享于 

3分钟阅读

ubuntu

  繁體

问题:

这是aws日志list-log-groups,输出是JSON格式,我需要grep第一个"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:



可以从Universe存储库安装jq:


sudo apt install jq



最好使用jq来解析json,但是没法用jq,并且格式不会改变,则可以使用grep -P和head -n1:


aws logs list-log-groups | grep -Po '"arn": "K[^"]*' | head -n1





COM  COMM  文本  TEX  PROC  Comma