Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell : Get a specific word under a sub section in yaml file

How do I get the value of nametag under metadata section of below yaml file.

    apiVersion: v1
    kind: Pod
    metadata:
      name: sss-pod-four
      namespace: default
    spec:
      containers:
      - name: sss-test-container
        image: anaudiyal/infinite-loop
        volumeMounts:
        - mountPath: "/mnt/sss"
          name: sss-test-volume
      volumes:
        - name: sss-test-volume

I need to get sss-pod-four string.

grep  "\sname: " config/pod.yaml | awk -F ": " '{print $2}'

The above code is printing sss-pod-four , sss-test-container and sss-test-volume

like image 739
ambikanair Avatar asked Dec 18 '22 00:12

ambikanair


2 Answers

Could you please try following and let me know if this helps you.

awk '/metadata/{flag=1} flag && /name:/{print $NF;flag=""}'  Input_file

Adding a non one liner form of solution with explanation too now:

awk '
/metadata/{         ##checking a string metadata in current line here and if it is TRUE then do following:
 flag=1}            ##Making a variable named flag value TRUE here.
flag && /name:/{    ##Checking if variable named flag is TRUE here and current line has string name: in it then do following:
  print $NF;        ##Printing the last column of the current line here.
  flag=""           ##Making variable named flag value as NULL here.
}
' Input_file        ##Mentioning Input_file name here.
like image 185
RavinderSingh13 Avatar answered Dec 21 '22 22:12

RavinderSingh13


You can also use this sed command to reach your goal:

$ sed -n '/metadata:/,/spec:/p' input.yml | grep -oP '(?<=name: ).*'
sss-pod-four
like image 44
Allan Avatar answered Dec 21 '22 22:12

Allan