Search code examples
unix-text-processing

Remove section from file based on its content


How can I remove the config section that contains config B2 in the following file using bash? Any quick solution using sed or awk or similar? The different sections are separated by an empty line if that helps.

Input file:

section X
    config A1
    config A2
    config A3

section Y
    config A1
    config B2
    config A3

section Z
    config C1
    config C2
    config A3

Expected output file:

section X
    option A1
    option A2
    option A3

section Z
    option C1
    option C2
    option C3

Solution

  • With awk:

    awk 'BEGIN { RS="section" } $0 !~ /config B2/ { print RS$0 }' file
    

    Set the record separator to "section" in the begin block. Then when the record doesn't contain "config B2", print the record separator followed by the record.