Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

awk print 1st row with condition

Tags:

bash

awk

The command:

kubectl get pods -n hello | awk '$1 ~ "hello-uwsgi-deployment"  {print $1}'

outputs

hello-uwsgi-deployment-5b7498f864-4bfrx
hello-uwsgi-deployment-5b7498f864-h9rxz
hello-uwsgi-deployment-5b7498f864-qlg8z
hello-uwsgi-deployment-5b7498f864-r5nfs
hello-uwsgi-deployment-5b7498f864-vxr6x

How can I print only the first line with the above condition using awk?

I tried

kubectl get pods -n hello |
awk '($1 ~ "hello-uwsgi-deployment") && ('NR==1') {print $1}'

but it outputs nothing.

EDIT:kubectl get pods -n hello | awk '($1 ~ /hello-uwsgi-deployment/){print;exit}' this works perfectly.

How to get the same working with multiple conditional statements using == and NR==?

like image 745
MR.i Avatar asked Feb 09 '26 22:02

MR.i


2 Answers

If I got your question correctly, you want to print only first line which has string hello-uwsgi-deployment then could you please try following. I am also using exit so that it will NOT read whole Input_file and will save time for us.

kubectl get pods -n hello | awk '($1 ~ /hello-uwsgi-deployment/){print;exit}'


OR of you want to simply do search string in whole line then try following:

kubectl get pods -n hello | awk '/hello-uwsgi-deployment/{print;exit}'
like image 77
RavinderSingh13 Avatar answered Feb 12 '26 15:02

RavinderSingh13


You can redirect the output to head command:

kubectl get pods -n hello | awk '$1 ~ "hello-uwsgi-deployment"  {print $1}' | head -n 1
like image 29
rootkonda Avatar answered Feb 12 '26 15:02

rootkonda



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!