Search code examples
linuxbashshellsedcommand

sed command deleting content in the whole range while respecting the condition


There is a file of similar format:

# Lorem ipsum dolor sit amet, consectetur adipiscing elit.
# Donec vitae ex metus. Integer nec dui sit amet odio vehicula tincidunt ac eget justo.
#
[A8-LINER-ADJUSTEMENT]
type: q-first-party
id: 3.4.987
canOperate: true
hash: 9bf533ef77fddb43cdc4b96ca9eb68fc862d71e90bb05b98abc9d1050893c266

[A8-LINER-ADJUSTEMENT]
type: q-first-party
id: 5.2.987
canOperate: true
hash: c8939c165c3af4ae77e7d5030b43644721fb8225e2994e846ef129f7de49254b

[A8-LINER-ADJUSTEMENT]
type: q-third-party
id: 4.9.987
canOperate: false
hash: f9ddaeaad5ed2280fbb9660553ab0af8bf6ea0a5a4b0db432398f26470e557bf

The goal is to delete whole content between [A8-LINER-ADJUSTEMENT] (inclusive) and empty line (inclusive). While property type is q-third-party.

File after the command execution should be looking like this:

# Lorem ipsum dolor sit amet, consectetur adipiscing elit.
# Donec vitae ex metus. Integer nec dui sit amet odio vehicula tincidunt ac eget justo.
#
[A8-LINER-ADJUSTEMENT]
type: q-first-party
id: 3.4.987
canOperate: true
hash: 9bf533ef77fddb43cdc4b96ca9eb68fc862d71e90bb05b98abc9d1050893c266

[A8-LINER-ADJUSTEMENT]
type: q-first-party
id: 5.2.987
canOperate: true
hash: c8939c165c3af4ae77e7d5030b43644721fb8225e2994e846ef129f7de49254b

sed -i '/\[A8-LINER-ADJUSTEMENT\]/,/^$/ { /q-third-party/d; }' introduction-availe.dat

This command deletes only type: q-third-party lines as the removal of the content within the specified range was expected.


Solution

  • When you don't have [ characters outside he tags, you can create an ugly sed solution

    sed -z 's/\[A8-LINER-ADJUSTEMENT\][^[]*type: q-third-party[^[]*//g' file
    

    The [^[]* is a set of characters [], with everything except a [, so ^[, repeated 0 or more times *.