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.1k views
in Technique[技术] by (71.8m points)

sh - Replace one matched pattern with another in multiline text with sed

I have file with this text:

mirrors:
  docker.io:
    endpoint:
      - "http://registry:5000"
  registry:5000:
    endpoint:
      - "http://registry:5000"
  localhost:
    endpoint:
      - "http://registry:5000"

I need to replace it with this text in POSIX shell script (not bash):

mirrors:
  docker.io:
    endpoint:
      - "http://docker.io"
  registry:5000:
    endpoint:
      - "http://registry:5000"
  localhost:
    endpoint:
      - "http://localhost"

Replace should be done dynamically in all places without hard-coded names. I mean we should take sub-string from a first line ("docker.io", "registry:5000", "localhost") and replace with it sub-string "registry:5000" in a third line.

I've figure out regex, that splits it on 5 groups: (^ )([^ ]*)(:[^"]*"http://)([^"]*)(")

Then I've tried to use sed to print group 2 instead of 4, but this didn't work: sed -n 's/(^ )([^ ]*)(:[^"]*"http://)([^"]*)(")/12325/p'

Please help!


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

1 Reply

0 votes
by (71.8m points)

This might work for you (GNU sed):

sed -E '1N;N;/
.*endpoint:.*
/s#((S+):.*"http://)[^"]*#12#;P;D' file 

Open up a three line window into the file.

If the second line contains endpoint:, replace the last piece of text following http:// with the first piece of text before :

Print/Delete the first line of the window and then replenish the three line window by appending the next line.

Repeat until the end of the file.


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

1.4m articles

1.4m replys

5 comments

57.0k users

...