0

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?

The Fool
  • 16,715
  • 5
  • 52
  • 86

1 Answers1

1

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" :  '.*://\([^/]*\)/')
chepner
  • 497,756
  • 71
  • 530
  • 681
  • Thanks, ns is an unkown part though. It could be any url path. Ideally the protocol is also variable like `*://` – The Fool Aug 03 '22 at 20:21
  • Updated. The `bash` regular expression can omit the protocol itself, and let the match start with the fixed string `://`. The `expr` regular expression is implicitly anchored to the start of the string, so you need to match everything that can proceed `://` as well. – chepner Aug 03 '22 at 20:29