skip to Main Content

I have many k8s deployment files with yaml format.

I need to get the value of the first occurrence of name option only inside these files.

Example of deployment.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  labels:
    app: nginx
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.14.2
        ports:
        - containerPort: 80

I need to get only the value nginx-deployment

I tried, but no success:

grep 'name: ' ./deployment.yaml | sed -n -e 's/name: /1/p'

3

Answers


  1. With sed. Find first row with name, remove everything before : and : and then quit sed.

    sed -n '/name/{ s/.*: //; p; q}' deployment.yaml
    

    Output:

    nginx-deployment
    
    Login or Signup to reply.
  2. If you have yq installed(similar to jq) for yaml, this is a yaml aware tool and perhaps a robust tool for parsing yaml.

    yq e '.metadata.name' deployment.yaml
    nginx-deployment
    

    Using awk :

    awk -v FS="[: ]" '/name:/{print $NF;exit}'  deployment.yaml
    nginx-deployment
    
    Login or Signup to reply.
  3. With GNU grep(1) that supports the -P flag.

    grep -m1 -Po '(?<=name: ).*' deployment.yaml 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search