Extract value of get parameter in shell
Clash Royale CLAN TAG#URR8PPP
Extract value of get parameter in shell
I have an input that could either be dn3321
or https://domaincom/file?tag=dn3321
and I'm trying to parse the value of tag using shell.
dn3321
https://domaincom/file?tag=dn3321
Looks like a regex could do the trick, how would I write a one liner to detect if it's a URL if it is apply the regex to extract the value and if its not just use the value directly.
2 Answers
2
It's unclear from the question what the full space of possible inputs looks like, but, for the simple cases you gave, you can use parameter expansion:
#!/usr/bin/env bash
in1='dn3321'
in2='https://domaincom/file?tag=dn3321'
echo "$in1#*="
echo "$in2#*="
# prints "dn3321" twice
This works by removing the first =
and any text preceding it.
=
It wasn't clear to me from the OP what the possible prefixes are (how should we handle
ftp://domaincom/file?tag=dn3321
? https://domaincom/file?tag=dn3321&foo=bar
? https://otherdomain.com/foo?bar=bat&tag=dn3321
?). So I went for the shortest example that would demonstrate the method.– Ollin Boer Bohan
Aug 12 at 3:26
ftp://domaincom/file?tag=dn3321
https://domaincom/file?tag=dn3321&foo=bar
https://otherdomain.com/foo?bar=bat&tag=dn3321
thank you! I can tweak the regex now but the format of the command was my struggle, I appreciate your help
– Newton
Aug 13 at 13:51
If you just need to print out a very specific part of the string that is a url you can do it like this:
#!/bin/bash
url="https://domaincom/file?tag=dn3321"
if [[ "$url" =~ "$http,," ]] ; then
tag=$(echo $url | cut -d'=' -f2)
fi
if you need something more elaborate I can post an example.
thank you! that helps
– Newton
Aug 13 at 13:52
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
you forgot the check for http ;-)
– Mike Q
Aug 12 at 3:07