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

Categories

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

bash - How to remove a child block from YML in shell script?

I'm trying to compare two yml files and removing a block based on some conditions using shell script. I'm using this YML parser, https://gist.github.com/pkuczynski/8665367 for the comparison of yml files. But I'm really strugglig a lot for removing the block from them. For example,

tool:
  image: tool.xxx.com/platform/app:dev
  log_driver: syslog
  restart: always
  ports:
    - "54325:80"
    - "543325:80"
  volume:
    - "a:b"

tool1:
  image: tool1.xxx.com/platform/app:dev
  log_driver: syslog
  restart: always
  ports:
    - "54325:80"
    - "543325:80"
  volume:
    - "a:b"

How to remove ports block under tool and which will make output similar to,

tool:
  image: tool.xxx.com/platform/app:dev
  log_driver: syslog
  restart: always
  volume:
    - "a:b"

tool1:
  image: tool1.xxx.com/platform/app:dev
  log_driver: syslog
  restart: always
  ports:
    - "54325:80"
    - "543325:80"
  volume:
    - "a:b"

I tried somethings using awk and sed, but I don't know exactly as it contains some complex condition involving multiple lines.

Any help or suggestion on this would be greatly helpful and much appreciated.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

You can use this awk command:

awk '$1 == "tool:"{t=1}
   t==1 && $1 == "ports:"{t++; next}
   t==2 && /:[[:blank:]]*$/{t=0}
   t != 2' file.yml

Explanation:

  • Set t=1 when we encounter tool: as first column
  • When t==1, make t=2 when we encounter 1st column in ports:
  • Reset to t=0 when t==2 and we get a line that ends with :
  • print each line when t != 2 (means we are not in tool: -> ports: section)

Output:

tool:
  image: tool.xxx.com/platform/app:dev
  log_driver: syslog
  restart: always
  volume:
    - "a:b"

tool1:
  image: tool1.xxx.com/platform/app:dev
  log_driver: syslog
  restart: always
  ports:
    - "54325:80"
    - "543325:80"
  volume:
    - "a:b"

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