1

I am trying to use grep or sed to extract a url from a string which looks like javascript:open_window("http://www.example.com/somescript.ext?withquerystring=true");

The javascript link is generated -- by an external application I have no control over -- each time, so I have to extract the URL to use it. I have tried and failed to use a whole host of combinations of grep and sed, which haven't worked.

2

Using sed:

sed -E 's/.*\("(.*)"\).*/\1/'

Example:

echo 'javascript:open_window("http://www.example.com/somescript.ext?withquerystring=true")' | sed -E 's/.*\("(.*)"\).*/\1/'
http://www.example.com/somescript.ext?withquerystring=true
6

Simply with GNU grep:

s='javascript:open_window("http://www.example.com/somescript.ext?withquerystring=true");'
grep -Eo 'http:[^"]+' <<<"$s"
http://www.example.com/somescript.ext?withquerystring=true
  • 1
    Doesn't make much sense to me to use grep -P if grep -E does the same. – Hauke Laging Jan 13 '18 at 18:12
  • @HaukeLaging, true, updated. (Unintentionally missed) – RomanPerekhrest Jan 13 '18 at 18:18
1
awk 'BEGIN {FS = "\42"} {print $2}' <<'eof'
javascript:open_window("http://www.example.com/somescript.ext?withquerystring=true");
eof
0

You could cut the output, specifying ' " ' (double quotes) as the delimiter.

$ invar='javascript:open_window("http://www.example.com/somescript.ext?withquerystring=true");'
$ echo $invar | cut -d '"' -f2
http://www.example.com/somescript.ext?withquerystring=true
0

I have achieved same by using below sed command

command

echo 'javascript:open_window("http://www.example.com/somescript.ext?withquerystring=true");'|  sed "s/.*(//g" l.txt  | sed 's/"//g' | sed "s/).*//g"

output

http://www.example.com/somescript.ext?withquerystring=true
  • (1) Why bother?  There are two sed answers ahead of yours, and they are both simpler than yours. (2) If you read the documentation, or any of the thousands of sed questions on this site, you’ll see that you hardly ever need to pipe sed into sed.  A three-sed pipeline is definitely unnecessary. – Scott Jan 18 '18 at 1:07
0
e='javascript:open_window("http://www.example.com/somescript.ext?withquerystring=true");'

The sed command will help:

sed -E 's/.*(http.*)\);/\1/' <<< "$e"
echo 'javascript:open_window("http://www.example.com/somescript.ext?withquerystring=true");' | sed -E 's/.*"(http.*)"\);/\1/'

Result:

http://www.example.com/somescript.ext?withquerystring=true

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.