0

I was not able to find a simple example of how to split an URL from port number after extracting them from an API call. So I wanted to put it here for anyone else looking for an answer.

APP_ENDPOINT=htttps://www.someURL.com:3333

I need to separate the URL from the PORT to make another call with them separated such as to ssh into the server.

This is the answer I came up with, does anyone have a more succinct answer?

Also this was for URL and port number but should work for IP:port # as well.

I used grep with regex to put the port # in one variable and sed to remove the the : and port # from the endpoint variable.

APP_ENDPIONT=https://www.someURLorIP:port#
APP_PORT=$(grep -Eo "[0-9]+$" <<< $APP_ENDPOINT)
APP_ENDPOINT=$(echo $APP_ENDPOINT | sed "s/:[0-9]*//")

This will give you two variables with the URL/IP and the port in their respective variables.

Don Davis
  • 7
  • 2
  • You could avoid external calls to `grep` and `sed` and just use *bash parameter expansion* https://www.cyberciti.biz/tips/bash-shell-parameter-substitution-2.html – Mark Setchell Aug 24 '22 at 07:33
  • Conventionally, you would put the answer included in your question into an actual answer... – Mark Setchell Aug 24 '22 at 07:35

1 Answers1

3

I will do like this:

APP_PORT=${APP_ENDPIONT##*:}

APP_ENDPOINT=${APP_ENDPIONT%:*}

And you can lookup the meaning of ${APP_ENDPIONT##*:} and ${APP_ENDPIONT%:*} in what-is-the-meaning-of-the-0-syntax-with-variable-braces-and-hash-chara

pppn
  • 66
  • 3