0

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!

Maddy
  • 1,319
  • 3
  • 22
  • 37

3 Answers3

2

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).

Community
  • 1
  • 1
tripleee
  • 175,061
  • 34
  • 275
  • 318
  • Agreed, that was a JSON tool would be apt here. But I was looking to solve this without a dependency on the tool. – Maddy Mar 02 '15 at 11:32
1

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
anubhava
  • 761,203
  • 64
  • 569
  • 643
0

Use this

 echo $b | sed 's/.*: \([^\}]*\)\}/\1/'

Or else,

 echo $b | sed 's/.*id: \([^\}]*\)\}/\1/'
Karthikeyan.R.S
  • 3,991
  • 1
  • 19
  • 31