Home > database >  How to get the substring after cetain char, and if the char doesn't exist, return empty
How to get the substring after cetain char, and if the char doesn't exist, return empty

Time:01-05

I have a string

VAR_A="127.0.0.1:12345"

I want to split it into HOSTNAME and PORT, with the delimiter :.

Per this post, I'm using this syntax to split the original VAR_A string:

HOSTNAME=${VAR_A%%:*}
PORT=${VAR_A#*:}

And it works if VAR_A if of the form xxxx:xxxx.

But I'd like to have the following result according to the value passed to VAR_A:

  • If VAR_A doesn't contain the char :, e.g. VAR_A=127.0.0.1, then HOSTNAME is assigned with 127.0.0.1, and assign empty string to PORT
  • If VAR_A contains the char : but nothing is after that :, e.g. VAR_A=127.0.0.1:, then same, HOSTNAME is assigned with 127.0.0.1, and assign empty string to PORT
  • If VAR_A contains the char : but nothing before that :, e.g. VAR_A=:12345, then assign empty string to HOSTNAME, and 12345 to PORT.

With current codes, if VAR_A=127.0.0.1, I got both HOSTNAME=127.0.0.1 and PORT=127.0.0.1, which is not desired.

If doable, I'd prefer a syntax similar to the one I provided -- the more succint/elegant the better.

CodePudding user response:

You can remove the first part with another parameter expansion:

VAR_A=127.0.0.1

HOSTNAME=${VAR_A%%:*}
PORT=${VAR_A#"$HOSTNAME"}
PORT=${PORT#:}

If there is no newline in VAR_A:

IFS=: read -r HOSTNAME PORT <<< "$VAR_A"

CodePudding user response:

If this is for a bash script, you can use if..else statements just like any other programming language.

I'd recommend checking out this tutorial page and creating some type of script that first checks to see if your string has the : character, then performing further actions as needed (e.g. parsing the left/right halves as needed for the HOST and PORT).

This is just one approach, of course; there are plenty other ways to do this.

  •  Tags:  
  • Related