user1652054
user1652054

Reputation: 465

How to parse URL params in shell script

I have tried the same successfully in python to parse URL params but I would like to know if there is a way to do the same in Shell Script.

Say, I have a URL value:

http://www.abcdsample.com/listservices?a=1&b=10&c=abcdeeff&d=1663889&listservices=a|b

Required Output:

URL: http://www.abcdsample.com/
Service: listservices
a=1
b=10
c=abcdeeff
d=1663889
listservices=a|b

Upvotes: 2

Views: 6622

Answers (2)

Chris Seymour
Chris Seymour

Reputation: 85785

Here is one method:

BEGIN{
    FS="?"
}
{
    url=$1
    sub(/[^/]*$/,"",url)
    print "URL:",url

    sub(/.*[/]/,"",$1)
    print "Service:",$1

    n=split($2,b,/&/)
    for (i=1;i<=n;i++)
        print b[i]
}

Save it as script.awk and run like awk -f script.awk file:

URL: http://www.abcdsample.com/
Service: listservices
a=1
b=10
c=abcdeeff
d=1663889
listservices=a|b

Note: this will work for URL like:

Upvotes: 5

Ed Morton
Ed Morton

Reputation: 203493

One way with GNU awk:

$ gawk -F'&' '{
   $0 = gensub(/(^[^/]+[/][/][^/]+[/])([^?]+)[?]/,"\\1\\&\\2\\&","")
   print "URL:",$1
   print "Service:",$2
   for (i=3;i<=NF;i++)
      print $i
}' file
URL: http://www.abcdsample.com/
Service: listservices
a=1
b=10
c=abcdeeff
d=1663889
listservices=a|b

Upvotes: 2

Related Questions