Reputation: 1379
I have a bash variable with the following value assigned to it:
# echo $b
{"tid": "session", "id": "9c7decd9-29d4-4d88-8fca-56d3b7b07bd5"}
When I try to extract the UUId from the variable 'b'
:
# temp=$(echo $b | awk '{print $4}')
# echo $temp
"9c7decd9-29d4-4d88-8fca-56d3b7b07bd5"}
...I get the additional flower bracket at the end. How do I just get the UUID?
Thanks!
Upvotes: 0
Views: 60
Reputation: 189367
What you have is JSON; so use a JSON tool to manipulate it.
jq -r .id <<<"$b"
If you want to retain the quotes, drop the -r
option.
Regardless of the tool you use, always put shell variables in double quotes unless you specifically require the shell to perform word splitting and wildcard expansion on the value.
The struggle to educate practitioners to use structure-aware tools for structured data has reached epic heights and continues unabated. Before you decide to use the quick and dirty approach, at least make sure you understand the dangers (technical and mental).
Upvotes: 2
Reputation: 785058
You can use grep -oP
with a PCRE regex:
b='{"tid": "session", "id": "9c7decd9-29d4-4d88-8fca-56d3b7b07bd5"}'
temp=$(grep -oP '"id": +"\K[^"]+' <<< "$b")
echo "$temp"
9c7decd9-29d4-4d88-8fca-56d3b7b07bd5
Upvotes: 1
Reputation: 4041
Use this
echo $b | sed 's/.*: \([^\}]*\)\}/\1/'
Or else,
echo $b | sed 's/.*id: \([^\}]*\)\}/\1/'
Upvotes: 0