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

I need to get nonce from http service. I use curl and later openssl to calculate sha1 of this nonce. but for this i need to get nonce for the 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 contains the http response

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 need to get the position "nonce =" and extract all the way to "char. How can I get into bash, the value is nonce ??

Hi

+4
source share
2 answers

Pretty simple grepusing options -o/ --only-matchingand -P/ --perl-regexp(available in GNU grep):

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

-o , nonce=", reset match start escape-, PCRE.

, output.txt ( ) nonce, , -m1 ( ):

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

nonce , substitution; openssl sha1, :

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

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

GNU sed , :

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==

!

0

Source: https://habr.com/ru/post/1686828/


All Articles