Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

sed - 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could use this awk:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.7k users

...