Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...