AWK/Grep并打印所有匹配记录



我有这个命令,它显示搜索中的所有记录。但我只想筛选与搜索词匹配的记录。

例如

for user in $(aws iam list-users |grep -i UserName|sed -e 's/.*: "//' -e 's/",//'); do 
echo USER: $user; 
echo TAGS:
aws iam list-user-tags --user-name $user --output text | awk '{print $2,$3}'
echo GROUPS:
aws iam list-groups-for-user  --user-name $user --output text|awk {'print $5'};  done > users.txt

上面的命令显示以下结果。

User: joe.blogs@abc.com
TAGS:
Team red
Status active
Environment: nonprod
GROUPS:
iam-nonprod
iam-prod
User: black.smith@abc.com
TAGS:
Team green
Status active
Environment: nonprod
GROUPS:
iam-nonprod
iam-prod
etc.

我想让所有的用户标签团队==红色。

我试着用第4行的搜索字符串,比如

aws iam list-user-tags --user-name $user --output text | awk '/red/{print $2,$3}'
but it displays only one line
Team red
But I would like to display full record like
User: joe.blogs@abc.com
TAGS:
Team red
Status active
Environment: nonprod
GROUPS:
iam-nonprod
iam-prod

你能帮助我如何显示标记Team==red的所有记录吗?

对于awk,您可以使用段落模式。这将显示所有";记录";其包含CCD_ 1。

awk -v RS= '/Team red/'

您可以通过各种awscli命令和使用--query选项来解决此问题,该选项允许您执行有条件的客户端筛选。

这里有一个例子:

#!/bin/bash
USERS=$(aws iam list-users --query "Users[*].UserName" --output text)
for user in $USERS; do
TAG=$(aws iam list-user-tags --user-name $user --query 'Tags[?(Key==`Team` && Value==`red`)]' --output text)
if [ "$TAG" != "" ]; then
echo "User:" $user
echo "Tags:"
aws iam list-user-tags --user-name $user --query 'Tags[*].[Key,Value]' --output text | tr "t" "="
echo "Groups:"
aws iam list-groups-for-user --user-name $user --query "Groups[*].GroupName" --output text | tr "t" "n"
fi
done

样本输出:

User: jason
Tags:
Team=red
Role=development
Groups:
dev
User: mary
Tags:
Team=red
Role=test
Groups:
qa
ut
fv

使用AWK非常简单。首先把你的数据放在一个文件中,这个命令将完成整个工作:

awk '/Team red/{c=4} c-->-2' < file
$ cat myfile
User: joe.blogs@abc.com
TAGS:
Team red
Status active
Environment: nonprod
GROUPS:
iam-nonprod
iam-prod
User: black.smith@abc.com
TAGS:
Team green
Status active
Environment: nonprod
GROUPS:
iam-nonprod
iam-prod
etc.
$ awk '/Team red/{c=4} c-->-2' < file
User: joe.blogs@abc.com
TAGS:
Team red
Status active
Environment: nonprod
GROUPS:
iam-nonprod
iam-prod
[brhosh@scp-3-scripting(enm2) test]$ 

相关内容

  • 没有找到相关文章

最新更新