在bash中解析变量 - 逐行并将值存储在另一个变量中

时间:2016-12-12 14:38:49

标签: bash shell parsing console output

我正在编写一个nagios脚本,如果我的任何AWS服务限制即将达到其阈值,它将提醒我。

我现在拥有的:

data = $form.serialize();

并且上述命令的输出为

aws --profile=profile-name support describe-trusted-advisor-check-result --language en --check-id eW7HH0l7J9 --query "result.sort_by(flaggedResources[],&metadata[2])[].metadata" --output text --region us-east-1 | grep Yellow

我想逐行解析输出并收集值:region和service;通知用户相同的内容。

例如,我想通知用户

eu-west-1   VPC Internet gateways   5   4   Yellow
eu-west-1   VPC VPCs    5   4   Yellow

任何建议?

2 个答案:

答案 0 :(得分:1)

如果我们假设为"黄色"是你的条件,以下应该做的伎俩。你觉得怎么样?

aws --profile=profile-name support describe-trusted-advisor-check-result --language en --check-id eW7HH0l7J9 --query "result.sort_by(flaggedResources[],&metadata[2])[].metadata" --output text --region us-east-1 | grep Yellow |\
awk -F"\t" '{print "The", $3, "has reached its limit in region", $1}'

答案 1 :(得分:1)

使用bash process substitution <()。将以下行放在sample.sh中,设置执行权限chmod +x sample.sh并以bash script.sh

运行脚本
 #!/bin/bash

 while read -r first _ second third _ 
 do
      printf "%s %s %s\n" "The $second $third has reached its limit in region $first"
 done< <(aws --profile=profile-name support describe-trusted-advisor-check-result --language en --check-id eW7HH0l7J9 --query "result.sort_by(flaggedResources[],&metadata[2])[].metadata" --output text --region us-east-1 | grep Yellow)

立即运行脚本,

$ bash script.sh
The Internet gateways has reached its limit in region eu-west-1  
The VPCs 5 has reached its limit in region eu-west-1