Reputation: 1591
I want to extract the value of pt & userId in a variable in shell script.
I've below value set in a varibale which comes dynamically & need to extract pt & userId
{"pt":"PT-24fesxPGJIHOe714iaMV-13dd3872781-sin_pos","userId":"66254363666003"}
Can any one tell me how to extract these values in shell script?
Note: I don't want to use JSON parser just to parse 2 strings.
Thanks!
Upvotes: 0
Views: 4143
Reputation: 786091
This string appears to be a JSON string and its better to use dedicated JSPN parser like underscore for parsing this text. Once underscore cli
is installed you can do:
# extract pt
echo $jsonStr | underscore select '.pt'
# extract userId
echo $jsonStr | underscore select '.userId'
Though not recommended but if you really want to parse it in shell you can use awk like this:
awk -F, '$1 ~ "pt" {gsub(/[^:]+:"|"/, "", $1); print $1}
$2 ~ "userId" {gsub(/[^:]+:"|"}/, "", $2); print $2}'
OR even simpler:
awk -F'"' '{print $4 "\n" $8}'
Output:
PT-24fesxPGJIHOe714iaMV-13dd3872781-sin_pos
66254363666003
Upvotes: 1
Reputation: 443
You can use following script
var={"pt":"PT-24fesxPGJIHOe714iaMV-13dd3872781-sin_pos","userId":"66254363666003"}
echo $var
pt=`echo $var|cut -d, -f1|awk -F':' '{ print $2 }'`
echo $pt
userId=`echo $var|cut -d, -f2|awk -F':' '{ print $2 }'|tr -d '}'`
echo $userId
In this script stores values in 2 variables "pt" and "userId", which you can use.
Upvotes: 0