I am trying to get the hostname for a url. I am able to do it with 2 assignments but I want to do it in a single step.
#!/usr/bin/env sh
HELM_CHART=oci://foo.bar.io/ns/chart-name
host=${HELM_CHART#*//}
host=${host%%/*}
echo "$host"
# foo.bar.io
I am not able to figure out a pattern or combination of pattern to achieve this. I read that you can combine a pattern like shown here Remove a fixed prefix/suffix from a string in Bash. I try all sorts of combinations, but I can't get it working.
Is it possible to do in a single assignment?
CodePudding user response:
You can't do this with parameter expansion alone. You can with a regular expression match, though. In bash
,
[[ $HELM_CHART =~ ://([^/]*)/ ]] && host=${BASH_REMATCH[1]}
In POSIX shell,
host=$(expr "$HELM_CHART" : '.*://\([^/]*\)/')