Deleting portion of a text file and following lines using sed

awksedtext processing

I need to edit a file like the following:

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

the goal is to delete the lines starting with 'iface…inet6' and also delete the next few that start with space (can be none or more than one):

iface wlx000 inet6 auto
  post-up sysctl -w net.ipv6.conf.wlx000.accept_ra=2

and keep the rest intact for the following result:

auto wlx00
allow-hotplug wlx00
iface wlx000 inet dhcp
auto wlx000

I tried with sed using as follows:

sed -i.old -r -e "/iface\s*\w*\s*inet6.*/,\${d;/^\s.*/d;}" /etc/configfile

but it removes everything starting at the right place but erasing to the end. I just want to remove lines staring with space after the select iface text.

Best Answer

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.

Related Question