Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract parent url from header with bash script

I have some time trying to get some part of a text (a header) on bash script but I couldn't. This is the string I have:

link: <https://api.some.com/v1/monitor/zzsomeLongIdzz?access_token=xxSomeLongTokenxx==>; rel="monitor",<https://api.some.com/v1/services/xx/something-more/accounts/2345?access_token=xxSomeLongTokenxx==>; rel="parent"

Here is with some format so you could see it better:

link: 
<https://api.some.com/v1/monitor/zzsomeLongIdzz?access_token=xxSomeLongTokenxx==>; rel="monitor",
<https://api.some.com/v1/services/xx/something-more/accounts/2345?access_token=xxSomeLongTokenxx==>; rel="parent"

I need the second part, just the url, basically the values between ,< and >; rel="parent" and assign that to a variable, like:

my_url = $(echo $complete_header) <== some way to filter that

I have no idea how to apply some regex or pattern to extract the data I need. On the past I had use jq for filtering json responses, like this:

error_message=$(echo $response | jq '.["errors"]|.[0]|.["message"]')

But unfortunately for me, this is not a json. Could somebody point me on the right direction with that?

like image 313
Gepser Hoil Avatar asked Jun 09 '26 11:06

Gepser Hoil


1 Answers

Use the following code:

#!/bin/bash
link='<https://api.some.com/v1/monitor/zzsomeLongIdzz?access_token=xxSomeLongTokenxx==>; rel="monitor",<https://api.some.com/v1/services/xx/something-more/accounts/2345?access_token=xxSomeLongTokenxx==>; rel="parent"'
re=",<([^>]+)>"
# look for ,< literally
# capture everything that is not a > one or more times ([^>]+)
# look for the closing > literally
my_url="test"
if [[ $link =~ $re ]]; then my_url=${BASH_REMATCH[1]}; fi
echo $my_url

See a demo on ideone.com.

like image 174
Jan Avatar answered Jun 12 '26 10:06

Jan