1

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 -> 0.0.0.0:49187 5672/tcp -> 0.0.0.0:49188
5678/tcp -> 0.0.0.0:49189

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?

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
Cengiz
  • 113

2 Answers2

1

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}'
0
docker port <container-name> | while read -r line;do echo ${line##*:};done
Ipor Sircer
  • 14,546
  • 1
  • 27
  • 39
  • 1
    you should avoid those while read... constructs: http://unix.stackexchange.com/questions/169716/why-is-using-a-shell-loop-to-process-text-considered-bad-practice/169765#169765 – 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