5

In shell, I need to extract specific query parameter from URI.

I tried to play around with this to get "offset" value

echo "/mypath/index.php?offset=20&query=uro" | perl -MURI -le 'chomp($url = <>); print URI->new($url)->query_form("offset")'

But it always returns just offset=20&query=uro

Please help

3 Answers 3

4

query_form returns a hash, change your script to:

perl -MURI -le 'chomp($url = <>); print +{URI->new($url)->query_form}->{offset}'

In order to process multiple lines:

perl -MURI -nle 'print +{URI->new($_)->query_form}->{offset}'
Sign up to request clarification or add additional context in comments.

1 Comment

What is the way to print 'offset' for each line from output, ex. I have: echo "/mypath/index.php?offset=20&query=uro \n /mypath2/index.php?offset=30&query=uro"
3

You can use the URI::QueryParam module in addition to URI.The query_param method in the URI::QueryParam module gives you query parameter values.

echo "/mypath/index.php?offset=20&query=uro" | perl -MURI -le 'use URI::QueryParam; chomp($url = <>); print URI->new($url)->query_param(offset);'

Comments

1

You can use the core CGI module:

perl -MCGI=param -e 'print param("offset")' "index.php?offset=20&query=uro"

2 Comments

for a strange reason it doesn't work with piped input... It is important as I am extracting that string there
@glaz666 CGI expects a query as an argument to the script. You could use echo "/mypath/index.php?offset=20&query=uro" | perl -MCGI=param -e '@ARGV=<>; print param("offset")'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.