Home > Blockchain >  how get text value of name option in k8s yaml file
how get text value of name option in k8s yaml file

Time:11-02

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'

CodePudding user response:

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

CodePudding user response:

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

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

Output:

nginx-deployment
  • Related