Search code examples
sedyamlindentation

Add new line with previous line's indentation


I'm struggling since a moment now to update some yaml files by adding an element in a new line with sed.

The sed command (or another linux command) must match a string (image: or - image:), add a new element on a new line with the same indentation as previous line.

The thing is that the new line must be exactly just under the string image: and not under - image:.

Example: When the sed matches the string image, it adds the new line with correct indentation (just above image)

kind: DaemonSet
apiVersion: apps/v1
metadata:
  name: calico-node
spec:
  template:    
    spec:      
      containers:        
        - name: calico-node
          image: myimage    
          imagePullSecret: mysecret
...

Example 2: when the sed matches the string - image, it adds the new line with correct indentation (just above image and not -):

kind: DaemonSet
apiVersion: apps/v1
metadata:
  name: calico-node
spec:
  template:    
    spec:      
      containers:
      - image: myimage    
        imagePullSecret: mysecret
...

What is not wanted is

kind: DaemonSet
apiVersion: apps/v1
metadata:
  name: calico-node
spec:
  template:    
    spec:      
      containers:
      - image: myimage    
      imagePullSecret: mysecret

I already tried the yq command to deal with this but it's a gigantic pain...

I found this code in another thread but it doesn't work when matching the - image string.

sed '/^ *image: .*/ { G; s/^\( *\)image: .*/&\1imagePullSecret: mysecret/; }' sed.yaml

Solution

  • You could use this awk:

    awk '/^[[:space:]-]*image/{ split($0,arr,/image.*/) 
                               gsub(/-/," ", arr[1])
                               rep=arr[1]
                               print $0}
                           rep{ printf "%s%s\n", rep, "imagePullSecret: mysecret"
                           rep=""
                           next} 1' file