user2328273
user2328273

Reputation: 968

extract text between single quotes in mult line variable with sed

I am trying to write a script. I use a remote procedure call with xmlrpc to get a url. I assign the output as a variable all in one command like url=$(xmlrpc 192.168.1.1 command...) for example. This is the output of the procedure call when output to a file:

Result:

String: 'http://example.url'

It all shows up on one line with echo $url. When I try to extract the URL between the single quotes with sed s/^.*'\(.*\)'.*$/\1/ $url I get the following:

sed: can't read Result:: no such file or directory
sed: can't read String:: no such file or directory
sed: can't read http://example.url: no such file or directory

Maybe the multiple lines is the problem. I get a similar error with grep -oP "(?<=').*?(?=')" $url Any ideas? I just want to extract the URL.

Upvotes: 3

Views: 6241

Answers (3)

ArturFH
ArturFH

Reputation: 1787

sed -n "s/^.*'\(.*\)'.*$/\1/ p" <<< ${url}

Upvotes: 2

mauro
mauro

Reputation: 5950

I think you should give native bash regex and replacement a try. If you really want to extract the URL from your multiline variable:

$ echo "$url"
Results:

String: 'http://example.url'

with sed, then you can use something like this:

$ url=$(sed -n "s/^.*'\(.*\)'.*$/\1/p" <<< $var)
$ echo "$url"
http://example.url

Upvotes: 1

RomanPerekhrest
RomanPerekhrest

Reputation: 92884

With bash regular expresssions:

[[ "$url" =~ \'(http:[^\']*)\' ]] && echo ${BASH_REMATCH[1]}
http://example.url

Upvotes: 2

Related Questions