Issue
I have this JSON String:
{"name":"http://someUrl/ws/someId","id":"someId"}
I just want to get value for "id" key and store it in some variable. I succesfully tried using jq. But due to some constraints, I need to achieve this just by using grep and string matching.
I tried this so far: grep -Po '"id":.*?[^\\]"';
But that is giving "id":"ws-4c906698-03a2-49c3-8b3e-dea829c7fdbe"
as output. I just need the id value. Please help
Solution
With a PCRE regex, you may use lookarounds. Thus, you need to put "id":"
into the positive lookbehind construct, and then match 1 or more chars other than "
:
grep -Po '(?<="id":")[^"]+'
where
(?<="id":")
- requires a"id":"
to appear immediately to the left of the current position (but the matched text is not added to the match value) and[^"]+
- matches and adds to the match 1 or more chars other than"
.
To get the values with escaped quotes:
grep -Po '(?<="id":")[^"\\]*(?:\\.[^"\\]*)*'
Here, (?<="id":")
will still match the position right after "id":"
and then the following will get matched:
[^"\\]*
- zero or more chars other than"
and\
(?:\\.[^"\\]*)*
- zero or more consequent sequences of:\\.
- a\
and any char (any escape sequence)[^"\\]*
- zero or more chars other than"
and\
Answered By - Wiktor Stribiżew