Home > database >  How to split a URL and Port stored in a variable and separate them into two variables URL and Port i
How to split a URL and Port stored in a variable and separate them into two variables URL and Port i

Time:08-24

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.

CodePudding user response:

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

CodePudding user response:

You could create an array to store the values.

$ APP_ENDPIONT=https://www.someURLorIP:port#
$ arr=($(sed -E 's/(.*):(.*)/\1 \2/' <<< "$APP_ENDPIONT"))
$ echo ${arr[0]}
https://www.someURLorIP
$ echo ${arr[1]}
port#
  • Related