Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

kubectl: get cut pod name

Im playing with "kubectl get pods...", and there is use case:

I have some pods returning(lets leave only names):

$ kubectl get pods | cut -d' ' -f1

admin-fe-124
admin-be-12345
some-Other-Staff-123

Question: is it possible to filter out (with kubectl get pods) only first eg 2 words(3...4...as i wish) of the name? I want to see following:

$ kubectl get pods... (some magic)

admin-be
admin-fe
some-Other

So, what should be there under "some magic"? Thanks!

like image 667
Dmitry Avatar asked Sep 02 '25 02:09

Dmitry


2 Answers

Do you mean print just the first column e.g. Names?

kubectl get po | awk '{print $1}'
NAME
kubeserve-68776dd94c-2wmc9
kubeserve-68776dd94c-qvg6c
kubeserve-68776dd94c-vqbcf
myreplicaset-gd6hj
myreplicaset-mfthn
myreplicaset-nsb9s
nginx-7db9fccd9b-hrp57
nginx-7db9fccd9b-m6t6l
ssd-monitor-lgmmr
ssd-monitor-m5sz6

You can then use

awk '{print $1, $2}' etc.

edit: or do you mean print the first two entries?

In which case just pipe the output to set and skip the first line e.g.

kubectl get po | awk '{print $1}' | sed -n 2,3p
kubeserve-68776dd94c-2wmc9
kubeserve-68776dd94c-qvg6c
like image 157
bob dylan Avatar answered Sep 06 '25 22:09

bob dylan


Using array and variable substitution

# test function to create needed output
test_names () {
    echo "
        admin-fe-124
        admin-be-12345
        some-Other-Staff-123
    "
}

test=( $(test_names) ) # create an array
echo "${test[@]%-*}"   # use variable substitution to cut last part

In your case

names=( $(kubectl get pods | cut -d' ' -f1) )
echo "${names[@]%-*}"
like image 21
Ivan Avatar answered Sep 07 '25 00:09

Ivan