Deleting portion of a text file and following lines using sed

Try this adaption of your sed one liner:

sed  '/iface\s*\w*\s*inet6.*/,/^[^ ]/ {/^[^ i]/!d}' file

It matches the range from your first pattern to the first line NOT starting with a space char, and deletes the lines starting with space or an "i" (for the leading iface). Need to rethink should the i be required after the block.

Looks like this works:

sed -n '/iface\s*\w*\s*inet6.*/ {:L; n; /^[ ]/bL;}; p' file

Pls try and report back.


A script for standard sed that uses an explicit loop to delete the lines:

/^iface .* inet6/ {
    :again
    N
    s/.*\n//
    /^[[:blank:]]/b again
}

The script finds the inet6 lines and then appends the next line to that line internally in the pattern space (with an embedded newline character in-between). It then deletes the pattern space up to and including the first newline character (this deletes the original inet6 line). It continues doing this until the pattern space does not start with a blank character (space or tab).

Testing:

$ cat file
auto wlx00
allow-hotplug wlx00
iface wlx000 inet dhcp
iface wlx000 inet6 auto
  post-up sysctl -w net.ipv6.conf.wlx000.accept_ra=2
auto wlx000
$ sed -f script.sed <file
auto wlx00
allow-hotplug wlx00
iface wlx000 inet dhcp
auto wlx000

Testing on artificial data:

$ cat file
something1
something2
iface have a inet6 here
   delete me
   me too
   same here
something3
something4
iface more something inet6
   be gone
   skip this
something5
$ sed -f script.sed <file
something1
something2
something3
something4
something5

The script as a "one-liner":

sed -e '/^iface .* inet6/ {' -e ':a' -e 'N;s/.*\n//;/^[[:blank:]]/ba' -e '}'

You've already got good answers for sed tool, but let me propose other, I believe much simpler, approach using pcregrep:

pcregrep -Mv '^iface.*inet6(.|\n )*' file

The regex should be self-explanatory - we search for pattern starting from the line ^iface.*inet6 and then group of any character OR new line followed by single space repeated zero or more times. Then we just need to instruct pcregrep to allow multi-linear matching with -M option and reverse the whole thing by -v (matched part will be removed).