Monday, February 26, 2024
 Popular · Latest · Hot · Upcoming
15
rated 0 times [  15] [ 0]  / answers: 1 / hits: 1811  / 10 Months ago, sat, may 27, 2023, 2:24:51

I want to extract the IP and Port from a variable. I have tried to use this:


ADDR=1.2.3.4:12345
IP=${ADDR##:}
PORT=${ADDR%:}

However, this assigns the entire address to both variables.


How can I store the the IP and Port to two variables?


More From » bash

 Answers
1

You got it wrong, has to be like this:


ADDR=1.2.3.4:12345
IP=${ADDR%:*}
PORT=${ADDR##*:}

Since there is only one matching occurrence of : for IPv4, in this case it doesn't matter if you match first or last occurrence. However, in case of IPv6, it's best to match last occurrence for port. In addition, it seems you accidentally switched IP and PORT.


Also see here: Bash cheatsheet and Bash Hacker wiki


In short, substring removal works like this:



  • ${variable#pattern}: Remove from the beginning of string, first match

  • ${variable##pattern}: Remove from the beginning of string, last match

  • ${variable%pattern}: Remove from the end of string, first match

  • ${variable%%pattern}: Remove from the end of string, last match


It can be necessary to include wildcard (*) in the pattern if you want to match only part of a word, that is not separated by whitespace.


[#21] Saturday, May 27, 2023, 10 Months  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
aciousoun

Total Points: 178
Total Questions: 110
Total Answers: 98

Location: Lithuania
Member since Fri, Sep 4, 2020
4 Years ago
aciousoun questions
;