Reputation: 13
I've got the following Problem:
I would like to alter the parameters of an URL. My idea was to first cut the parameters as a whole like that:
url="http://domain.com/file.php?par1=val1&par2=val2&par3=val3"
pars=$(cut -d"?" -f2 <<< $url)
So now
echo "$pars"
should give me a list of Parameters seperated by the "&" character.
par1=val1&par2=val2&par3=val3
I want to replace val1 with the variable $newpar then use curl to visit the website with the changed parameter. Then i want to change the parameter back to val1 and change val2 to $newpar and so on. My question is: How do I do that?
I don't know how much parameters there will be, because the $url variable is read out of a file with URLs with a different number of parameters. I think some kind of regex would come in handy and also that probably a for loop would do the trick. But I don't know exactly how.
Thank you very much in advance
Upvotes: 1
Views: 504
Reputation: 531125
Assuming var1
is specific enough, the following should work:
url=${url/par1=val1/par1=$newpar}
The only problem would be if par1
could be the suffix of another parameter, like
url="http://domain.com/file.php?par1=val1&otherpar1=val2&par3=val3"
In that case, use a regular expression to ensure par1
is preceded by either &
or ?
:
[[ $url =~ (.*)([?&])(par1=val1)(.*) ]]
url="${BASH_REMATCH[1]}${BASH_REMATCH[2]}par1=$newpar${BASH_REMATCH[4]}"
Element 1 contains everything before the ?
or &
that precedes the parameter you want to change. Element 2 contains the ?
/&
. Element 2 is the text you want to replace; we use the replacement text instead of that element. Finally, element 3 contains the text, if any, that follows the parameter you are changing.
Upvotes: 1