There IS a way to do it one step using only built-in bash functionality (no running external programs such as sed
) -- with BASH_REMATCH
:
url=http://whatever/score/
re='https?://(.*)/score/'
[[ $url =~ $re ]] && printf '%s\n' "${BASH_REMATCH[1]}"
This matches against the regular expression on the right-hand side of the =~
test, and puts the groups into the BASH_REMATCH
array.
That said, it's more conventional to use two PE expressions and a temporary variable:
shopt -s extglob
url=http://whatever/score/
val=${url#http?(s)://}; val=${val%/score/}
printf '%s\n' "$val"
...in the above example, the extglob
option is used to allow the shell to recognized "extglobs" -- bash's extensions to glob syntax (making glob-style patterns similar in power to regular expressions), among which ?(foo)
means that foo
is optional.
By the way, I'm using printf
rather than echo
in these examples because many of echo
's behaviors are implementation-defined -- for instance, consider the case where the variable's contents are -e
or -n
.