【问题标题】:How to use jq with 'select(startswith("$variable"))'?如何将 jq 与 'select(startswith("$variable"))' 一起使用?
【发布时间】:2017-12-22 10:23:58
【问题描述】:

我正在使用 jq 解析来自 AWS cli 的一些输出。

我正在尝试使用'select(startswith("$variable") )',但由于某种原因,即使我使用变量的值,它也无法正常工作。

例子:

itai@MacBook-Pro ~/src/Scripts - $ echo $App
Analytics
itai@MacBook-Pro ~/src/Scripts - $ aws cloudformation describe-stacks --stack-name $StackName --region $region | jq -r '.Stacks[].Outputs[].OutputKey | select(startswith("Analytics") )'
AnalyticsAutoScalingGroup
itai@MacBook-Pro ~/src/Scripts - $ aws cloudformation describe-stacks --stack-name $StackName --region $region | jq -r '.Stacks[].Outputs[].OutputKey | select(startswith("$App") )'
itai@MacBook-Pro ~/src/Scripts - $

我知道我可以像这样使用 grep:

aws cloudformation describe-stacks --stack-name $StackName --region $region | jq -r '.Stacks[].Outputs[].OutputKey' | grep $App

但我更喜欢在整个命令中使用 jq。

是我做错了还是不可能?

【问题讨论】:

    标签: aws-cli jq


    【解决方案1】:

    您也可以不使用--arg--argjson 来执行此操作。在您的情况下,由于您的变量包含一个字符串值,您可以这样做。

    aws cloudformation describe-stacks --stack-name $StackName --region $region |\
    jq -r '.Stacks[].Outputs[].OutputKey | select(startswith('\"$App\"') )'
    

    请注意,我添加了单引号并转义了变量周围的双引号

    请参阅此处https://github.com/stedolan/jq/wiki/FAQ环境变量如何传递给 jq 程序?如何参数化 jq 程序?”第二个答案。

    【讨论】:

      【解决方案2】:

      通常,将 shell 变量的值传递给 jq 程序的最佳方法是使用-—arg 和/或—-argjson 命令行选项,如手册中所述。环境变量可以使用env传入。

      另见https://github.com/stedolan/jq/wiki/FAQ

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多