0

I have a JSON structure like this which I've read into a bash variable as a string:

{
        "elem1": "val1",
        "THEELEM": "THEVAL",
        "elem3": "val3"
}

I want to use regex to match on "THEELEM": "THEVAL". It works if I try individual words, where the JSON is stored in result as a string:

[[ $result =~ THEVAL ]] && echo "yes"

But I want to match on the key-pair like this:

[[ $result =~ "THEELEM": "THEVAL" ]] && echo "yes"

That gives me syntax issues. I've tried escaping, single-quotes and triple quotes to no avail. Any help appreciated.

1
  • 6
    More generally, you should use the jq utility to parse JSON in bash. Commented Jun 11, 2019 at 21:39

2 Answers 2

1

Quoting works for me.

[[ $result =~ '"THEELEM": "THEVAL"' ]] && echo "yes"

Note that quoting the pattern disables recognition of special regular expression characters, and just searches for the literal substring. This is not a problem here, since you don't have any wildcards or other non-literal pattern characters. But if you did, you'd have to put the pattern in a variable, as in @noah's answer.

Sign up to request clarification or add additional context in comments.

2 Comments

...though it's an exact substring match rather than a regex match in this usage mode.
@CharlesDuffy Good catch. The man page on my Mac doesn't mention that (although it's true in the implementation), but I found the explanation in the online bash manual.
1

You can create a variable $expr to hold the string you want to match to and then use that for the regex.

expr='"THEELEM": "THEVAL"'
[[ $result =~ $expr ]] && echo "yes"

Inspired by this stack overflow post

1 Comment

You can't have blanks around = in an assignment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.