Mr.Stranger Mr.Stranger - 6 months ago 25
Bash Question

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.

Answer

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"
Comments