Let's say I have the following JSON string in a Bash script variable, DATA
:
{
"id": 10,
"name": "Person 1",
"note": "This is a test"
}
I need to get the value of the name
field. I have used grep
like this:
NAME=$(echo "$DATA" | grep -E "\"name\": \"(.*)\"")
However, this returns "name": "Person 1"
. I need Person 1
. How can I get the result of just the (.*)
?
Best Answer
You can do this easily with
jq
:In general, it's best to avoid regex for parsing structured data such as html, json, and yaml.
To accomplish this with grep, you need to use PCRE to leverage look-aheads and look-behinds: