"regular expression compile failed (missing operand)" issue in AWK when checking for an asterisk

10/12/2021

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)
-- Eyal Solomon
awk
kubernetes

2 Answers

10/18/2021

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 https://stackoverflow.com/questions/65621325/how-do-i-find-the-text-that-matches-a-pattern for the difference):

k config get-contexts | awk '$1=="*"{ print $5 }'
-- Ed Morton
Source: StackOverflow

10/12/2021

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.

-- Wiktor Stribiżew
Source: StackOverflow