How to parse a string of a kubectl cmd output in a shell script?

kubectl get nodes -o name gives me the output

node/k8s-control.anything
node/k8s-worker1.anything

I need to get only

control
worker1

as output and want to iterate through these elements

for elm in $(kubectl get nodes -o name); do echo "$elm" >> file.txt; done

So the question is how to get the string between node/k8s- and .anything and iterate these in the for loop.

>Solution :

You can for example use cut twice, first to get a part after - and
then to get a part before .:

for elm in $(kubectl get nodes -o name | cut -d- -f2 | cut -d. -f1); do echo "$elm" >> file.txt; done

Leave a Reply