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

Time:09-23

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.

CodePudding user response:

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

CodePudding user response:

With awk

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

CodePudding user response:

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

CodePudding user response:

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)
  • Related