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

How to delete a main block from YML

I have a YML file with content similar to,

test:
volumes:
- /u01/test-service/conf:/root/config

testmanager:
port:
- "2222:80"


I want to delete test or testmanager block based on some conditions. Here is the awk expression I found here,

awk '{sub(/\r$/, "")}
$1 == "test:"{t=1}
t==1 && $1 != "test:" {t++; next}
t==2 && /:\s*$/{t=0}
t != 2'


This deletes everything under test but keeps the string "test:". Something like this,

reportservice:
reportmanager:
port:
- "2222:80"


How to fix this? Please help.

Answer

With the shown input you can use this awk command with empty RS:

awk -v RS= '!/^[[:blank:]]*test:/' file.yml

testmanager:
  port:
    - "2222:80"

This assumes there is an empty line between each block. If this doesn't work you can modify your existing command you can do:

awk '{sub(/\r$/, "")}
     $1 == "test:"{t=1}
     t==1 && $1 != "test:" {t++; next}
     t==2 && /:\s*$/{t=0}
    !t' file.yml