AhmFM
AhmFM

Reputation: 1802

Using awk how to print selective columns when a condition is met

Problem: I want to list all pods matching expression "test-" for which my expression works well and then I want to print only $1 and $2 if that expression exists in row. how can I? I want to do this with single AWK and not pipe again.

 kubectl get pods --all-namespaces --field-selector=spec.nodeName=node1,status.phase!=Succeeded --no-headers | awk '$1 ~ /maglev-/'

output

test-78ac951e-89a6-4199-87a4-db8a1b8b054f   export-4cb52be4-8a90-400-ilxr4b-avexport-xavierisp-sjc4--b76888-b3f   1/1   Running   0     20h
test-78ac951e-89a6-4199-87a4-db8a1b8b054f   export-9b55f0d5-071d-431-1d2ux0-avexport-xavierisp-sjc4--a4dd85-102   1/1   Running   0     17h
dtlu @ dtlu16 ~
└─ $ ▶ kubectl get pods --all-namespaces --field-selector=spec.nodeName=node1,status.phase!=Succeeded --no-headers | awk '$1 ~ /test-/' '{print $1,$2}'

output actual:

awk: cannot open {print $1,$2} (No such file or directory)

expected output

test-78ac951e-89a6-4199-87a4-db8a1b8b054f   export-4cb52be4-8a90-400-ilxr4b-avexport-xavierisp-sjc4--b76888-b3f

test-78ac951e-89a6-4199-87a4-db8a1b8b054f   export-9b55f0d5-071d-431-1d2ux0-avexport-xavierisp-sjc4--a4dd85-102

Upvotes: 1

Views: 320

Answers (2)

Inian
Inian

Reputation: 85865

You have an incorrect awk syntax by providing '{$1, $2}' in separate quotes after the pattern match. They need to be combined together as one. The syntax you have makes awk believe that '{$1, $2}' as file name to run the expression on.

awk '$1 ~ /test-/{print $1, $2}'

Upvotes: 2

Anton Malyshev
Anton Malyshev

Reputation: 8871

Isn't that as simple as:

kubectl get pods --all-namespaces --field-selector=spec.nodeName=node1,status.phase!=Succeeded --no-headers | egrep "^test-" | awk '{print $1" "$2}'

?

Upvotes: 0

Related Questions