What does "\ K" mean in this regular expression?

Given the following shell script, would anyone be so kind as to explain the grep -Po ?

 #!/bin/bash # Issue the request for a bearer token, json is returned raw_json=`curl -s -X POST -d "username=name&password=secret&client_id=security-admin-console" http://localhost:8081/auth/realms/master/tokens/grants/access` # Strip away all but the "access_token" field value using a Python regular expression bearerToken=`echo $raw_json | grep -Po '"'"access_token"'"\s*:\s*"\K([^"]*)'` echo "The bearer token is:" echo $bearerToken 

So specifically, I'm interested in understanding the parts of regex

 grep -Po '"'"access_token"'"\s*:\s*"\K([^"]*)'` 

and how it works. Why are there so many quotes? What is "K" for? I have experience with grep regex, but that bothers me.

This is the actual output of the curl command, and the shell script (grep) works as desired, returning only the contents of the "access_token" value.

{"access_token":".fQmQKn-xatvflHPAaxCfrrVow3ynpw0sREho7__jZo2d0g1SwZV7Lf4C26CcweNLlb3wmKHHo63HRz35qRxJ7BXyiZwHgXokvDJj13yuOb6Sirg9z02n6fwGy8Iog30pUvffnDaVnUWHfVL-h_R4-OZNf-_YUK5RcL2DHt0zUXI","expires_in":60,"refresh_expires_in":1800,"refresh_token":"eyJhbGciOiJSUzI1NiJ9..WeiJOC1jQ52aKgnW8UN2Lv9rJ_yKZiOhijOYKLN2EEOkYF8rvRZsSKbTPFKTIUvjnwy2A7V_N-GhhJH4C-T7F5__QPNofSXbCNyvATj52jGLxk9V0Afvk-Z5QAWi55PJRTC0qteeMRcO2Frw-0KtKYe9o3UcGICJubxhZHsXBLA","token_type":"bearer","id_token":"eyJhbGciOiJSUzI1NiJ9.eyJuYW1lIjoiIiwianRpIjoiMGIyMGI0ODctOTI4OS00YTFhLTgyNmMtM2NiOTg0MDJkMzVkIiwiZXhwIjoxNDQ2ODI4MDU5LCJuYmYiOjAsImlhdCI6MTQ0NjgyNzk5OIwouldhaveToBeNutsUiLCJwcmVmZXJyZWRfdXNlcm5hbWUiOiJhZG1pbiIsImVtYWlsX3ZlcmlmaWVkIjpmYWxzZX0.DmG8Lm4niL1djzNrLsZ2CrsB1ZzUPnR2Nm7IZnrwrmkXsrPxjl6pyXKCWSj6pbk2sgVI8NNFqrGIJmEJ7gkTZWm328VGGpJsmMuJBki0KbqBRKORGQSgkas_34rwzhcTE3Iki8h_YVs2vvNIx_eZSOvIzyEcP3IGHuBoxcR6W3E","not-before-policy":0,"session-state":"62efc05c-1bf5-4f55-b749-5e0eff94155b"}




In case anyone finds this post, here is what I ended up using:

if hash jq 2>/dev/null; then # Use the jq command to safely parse json bearerToken=$(echo $raw_json | jq -r '.access_token') else # Strip away all but the "access_token" field value using a perl regular expression bearerToken=$(echo $raw_json | grep -Po '"'"access_token"'"\s*:\s*"\K([^"]*)') fi

+11
bash regex grep
Nov 06 '15 at 19:07
source share
1 answer

Since not all regular expression flavors support lookbehind, Perl introduced \K Usually when you have:

 a\Kb 

When "b" matches, \K tells the engine to pretend that an attempt to match started at that position.

In your example, you want to pretend that an attempt to match began with what appears after "access_token": "text.

In this example, it is better to demonstrate the use of \K :

 ~$ echo 'hello world' | grep -oP 'hello \K(world)' world ~$ echo 'hello world' | grep -oP 'hello (world)' hello world 
+20
Nov 06 '15 at 19:12
source share



All Articles