-7

I am trying to create some useful aliases for myself and am trying to find a way see the current Kubernetes context namespace.

k config get-contexts

CURRENT   NAME                          CLUSTER      AUTHINFO           NAMESPACE
 *        kubernetes-test@kubernetes2   kubernetes2  kubernetes-test    test
          kubernetes-admin@kubernetes   kubernetes   kubernetes-admin   default

I only want the output to be 'test', so I tried:

k config get-contexts | awk '/*/{print $5}'

The error it gets:

awk: line 1: regular expression compile failed (missing operand)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Eyal Solomon
  • 470
  • 1
  • 6
  • 15

2 Answers2

2

You're getting that error message because * is a regexp repetition metachar and as such using it as the first char in a regexp is undefined behavior since there's nothing preceding it to repeat. You're also using a partial line regexp match when what you apparently want is a full word string match (see How do I find the text that matches a pattern? for the difference):

k config get-contexts | awk '$1=="*"{ print $5 }'
Ed Morton
  • 188,023
  • 17
  • 78
  • 185
0

First of all, * in regex is a quantifier that means "zero or more occurrences". Since it is a regex metacharacter, it should be escaped, \*:

k config get-contexts | awk '/\*/{print $5}'

However, since you are looking for a fixed string rather than a pattern you can use index:

k config get-contexts | awk 'index($0, "*") {print $5}'

If * is found anywhere inside a "record" (the line) the fifth field will get printed.

bad_coder
  • 11,289
  • 20
  • 44
  • 72
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563