user3142695
user3142695

Reputation: 17352

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.

Upvotes: 0

Views: 928

Answers (4)

j_b
j_b

Reputation: 2020

Another option might be bash parameter expansion:

while read -r line ; do line="${line#*-}"; line="${line%.*}";  printf "%s\n" "$line" ; done < <(kubectl get nodes -o name)

Upvotes: 0

P....
P....

Reputation: 18411

You can use grep with -oP filter to extract the desired substring. Later, you can use > operator to redirect to the file.txt.

kubectl get nodes -o name|grep -oP 'node.*?-\K[^.]+'
control
worker1

Upvotes: 0

Jetchisel
Jetchisel

Reputation: 7831

With awk

kubectl get nodes -o name | awk -F'[.-]' '{print $2}' > file.txt

Upvotes: 0

Arkadiusz Drabczyk
Arkadiusz Drabczyk

Reputation: 12528

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

Upvotes: 2

Related Questions