Monday, October 25, 2021

[SOLVED] Sed range and removing last matching line

Issue

I have this data:

One
  two
  three
Four
  five
  six
Seven
  eight

And this command:

sed -n '/^Four$/,/^[^[:blank:]]/p'

I get the following output:

Four
  five
  six
Seven

How can I change this sed expression to not match the final line of the output? So the ideal output should be:

Four
  five
  six

I've tried many things involving exclamation points but haven't managed to get close to getting this working.


Solution

You may pipe to another sed and skip last line:

sed -n '/^Four$/,/^[^[:blank:]]/p' file | sed '$d'

Four
  five
  six

Alternatively you may use:

sed -n '/^Four$/,/^[^[:blank:]]/{/^Four$/p; /^[^[:blank:]]/!p;}' file


Answered By - anubhava