Extract substring in bash from a file with pattern location from a given position to a special character

Viewed 205

I need to get a nonce from a http service I am using curl and later openssl to calculate the sha1 of that nonce. but for that i need to get the nonce to a variable

1 step (done)

curl --user username:password -v -i -X POST http://192.168.0.202:8080/RPC3 -o output.txt -d @initial.txt

and now, the output file @output.txt holds the http reponse

HTTP/1.1 401 Unauthorized
Server: WinREST HTTP Server/1.0
Connection: Keep-Alive
Content-Length: 89
WWW-Authenticate: ServiceAuth realm="WinREST", nonce="/wcUEQOqUEoS64zKDHEUgg=="

<html><head><title>Unauthorized</title></head><body>Error 401: Unauthorized</body></html>

I have to get the position of "nonce=" and extract all the way to the " char. How can I get in bash, the value of nonce ??

Regards

2 Answers

Pretty simple with grep using the -o/--only-matching and -P/--perl-regexp options (available in GNU grep):

$ grep -oP 'nonce="\K[^"]+' output.txt
/wcUEQOqUEoS64zKDHEUgg==

The -o option will print only matched part, which would normally include nonce=" if we had not used the reset match start escape sequence available in PCRE.

Additionally, if your output.txt (i.e. server response) can contain more than one nonce, and you are interested in only reading the first one, you can use the -m1 option (as Glenn suggests):

$ grep -oPm1 'nonce="\K[^"]+' output.txt

To store that nonce in a variable, simply use command substitution; or just pass it through openssl sha1 to get that digest you need:

$ nonce=$(grep -oPm1 'nonce="\K[^"]+' output.txt)
$ echo "$nonce"
/wcUEQOqUEoS64zKDHEUgg==

$ read hash _ <<<"$(grep -oPm1 'nonce="\K[^"]+' output.txt | openssl sha1 -r)"
$ echo "$hash"
2277ef32822c37b5c2b1018954f750163148edea

You can use GNU sed for this as below :

ubuntu$ cat output.txt
HTTP/1.1 401 Unauthorized
Server: WinREST HTTP Server/1.0
Connection: Keep-Alive
Content-Length: 89
WWW-Authenticate: ServiceAuth realm="WinREST", nonce="/wcUEQOqUEoS64zKDHEUgg=="

<html><head><title>Unauthorized</title></head><body>Error 401: Unauthorized</body></html>

ubuntu$ sed -E -n  's/(.*)(nonce="\/)([a-zA-Z0-9=]+)(")(.*)/\3/gp' output.txt
wcUEQOqUEoS64zKDHEUgg==

Regards!

Related