I want to parse the port number that I need from the output of the docker port command. The docker port <container-name> command returns output as follows:

15672/tcp -> 5672/tcp ->
5678/tcp ->

So it is either a single port number or 2 port numbers.

Thankfully, in the case that the command spews out 2 port numbers, I always need only the second one displayed. To clarify, in the two examples above, I need to parse out 49188 and 49189 port values from the output of the docker port command.

What is the shortest way of achieving this?

  • 2
    sed 's/.*://' or awk -F: '{print $NF}' applied to that output would output anything after the last : – Stéphane Chazelas Nov 22 '16 at 10:25

Sounds like a simple job for sed:

docker port <container-name> | sed 's/^.*:\([0-9]*\)$/\1/'

Or if you prefer awk:

docker port <container-name> | awk -F':' '{print $NF}'
docker port <container-name> | while read -r line;do echo ${line##*:};done
  • 1
    you should avoid those while read... constructs: unix.stackexchange.com/questions/169716/… – Valentin B. Nov 22 '16 at 10:18
  • @ValentinB.: show us the correct with ksh builtins only. – Ipor Sircer Nov 22 '16 at 10:24
  • 1
    If you want to do it with built-ins only, your way is the best indeed. But what's wrong with using sed or gawk? Most if not all ksh implementation will have them readily available. Some features of those tools will be implementation-dependant, but for a straightforward case like this, you only need basic features that will be present on all standard implementations. – Valentin B. Nov 22 '16 at 12:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.