在bash脚本中将sed命令合并为一个命令

时间:2018-10-29 20:57:22

标签: bash sed jq

我想改进这一行:

aws_iam_role=$(aws iam get-role --role-name rl-company-admin --profile=company-bill |
jq -r '.Role.AssumeRolePolicyDocument.Statement[].Principal.AWS' |
sed "s/arn:aws:iam::123456789101:user\///g" |
grep tdunphy |
sed 's/"//g'|
sed 's/,//g')

这是未经处理的命令的原始输出:

aws iam get-role --role-name rl-company-admin --profile=company-bill
{
    "Role": {
        "Description": "company Admin Role", 
        "AssumeRolePolicyDocument": {
            "Version": "2012-10-17", 
            "Statement": [
                {
                    "Action": "sts:AssumeRole", 
                    "Effect": "Allow", 
                    "Principal": {
                        "AWS": [
                            "arn:aws:iam::123456789101:user/tdunphy", 
                            "arn:aws:iam::123456789101:user/user1", 
                            "arn:aws:iam::123456789101:user/user2", 
                            "arn:aws:iam::123456789101:user/user3", 
                        ]
                    }
                }
            ]
        }, 
        "MaxSessionDuration": 3600, 
        "RoleId": "AROAJGNAT3IXV7DIWSDCK", 
        "CreateDate": "2018-01-18T17:35:27Z", 
        "RoleName": "rl-company-admin", 
        "Path": "/", 
        "Arn": "arn:aws:iam::188087670762:role/rl-company-admin"
    }
}

如何使用一个sed语句来处理此文本,而不是使用多个sed语句?

5 个答案:

答案 0 :(得分:4)

可以在单个jq 命令中完成此操作,这样可以避免调用多个外部命令,例如grepsed等:

aws iam get-role --role-name rl-company-admin --profile=company-bill |
jq --arg u 'tdunphy' -r '
 .Role.AssumeRolePolicyDocument.Statement[].Principal.AWS[] |
 select(. | endswith($u)) | sub("arn:aws:iam::123456789101:user/"; "")'

输出:

tdunphy

答案 1 :(得分:3)

如果您确实愿意,它结合了所有sedgrep行的功能:

sed -n 's/arn:aws:iam::123456789101:user\///g; s/[,"]//g; /tdunphy/ {p}'

在情人眼中,这是否算是一种进步。

答案 2 :(得分:3)

将呼叫更改为object MyCustomTask extends AutoPlugin { ... lazy val myCustomTask = Def.task { runner.value.run("my.support.project.classpath.Utility") } override val projectSettings: Seq[Def.Setting[_]] = Seq( libraryDependencies += "com.h2database" % "h2" % "1.4.197" ) } 看起来像这样,那么您就不必剥离其他字符了:

jq

您也可以尝试以下操作:

jq -r '.Role.AssumeRolePolicyDocument.Statement[].Principal.AWS[]'
                                                               ^^ Add these

这可能有点简洁,但是您可以通过一个aws iam get-role --role-name rl-company-admin --profile=company-bill | \ jq -r '.Role.AssumeRolePolicyDocument.Statement[].Principal.AWS[] | split("/") | last' | \ grep tdunphy 调用来完成全部操作:

jq

答案 3 :(得分:1)

您可以

sed 's/[,"]//g' 

代替两个sed(如果只是一个单词)

答案 4 :(得分:1)

替换

sed "s/arn:aws:iam::123456789101:user\///g" |
grep tdunphy |
sed 's/"//g'|
sed 's/,//g'

使用

sed -n '/tdunphy/ {
        s/arn:aws:iam::123456789101:user\///g
        s/[,"]//g
        p
     '