33

How can i break jq string into lines, this is for long lines, when i put "\" query breaks.

vpcExists=$(aws ec2 describe-vpcs --profile $profile | jq -r --arg vpcId "$vpcId" '.[][] | \
 select(.VpcId == $vpcId) \
| .["State"]' \
)
3
  • and no result with tutorials .....?
    – ZF007
    Feb 9, 2018 at 19:14
  • The newlines are shell specific features. Single quotes in bash will allow you to enter literal newlines fine... it's not jq specific. Feb 9, 2018 at 19:40
  • thanks @JeffMercado that is confusing, but now i got it Feb 9, 2018 at 19:42

1 Answer 1

59

jq is fine with literal line breaks, so just add linefeeds anywhere without trying to escape them:

vpcExists=$(aws ec2 describe-vpcs --profile $profile |
    jq -r --arg vpcId "$vpcId" '
   .[][] 
     | select(.VpcId == $vpcId)
     | .["State"]' 
)

Here's a MCVE:

jq -r --arg vpcId "someId" '
   .[][] 
     | select(.VpcId == $vpcId)
     | .["State"]'  << 'EOF'


{ "Vpcs": [ {
            "VpcId": "someId",
            "InstanceTenancy": "default",
            "State": "available",
            "IsDefault": false
        } ] }
EOF
2
  • 8
    MCVE is Stack Overflow jargon for Minimal, Complete, and Verifiable example. There's more details about that at stackoverflow.com/help/minimal-reproducible-example
    – mbigras
    May 8, 2021 at 17:01
  • How to break up the query containing string interpolation?example: "(.foo)|(.bar)" Imagine that query is long and I would like to format it on mutiple lines
    – Dmitry z
    Jun 23, 2022 at 14:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.