tags:

views:

22

answers:

1

The syntax for this is:

sed -n '/Regex1/,/Regex2/p'

But this includes the lines where Regex1 and Regex2 are found, how can I exclude them?

For example:

abcd-Regex1

BlaBlaBla

abcd-Regex2

Then I only want: BlaBlaBla

A: 

You can do this with a simple state machine in awk:

pax> echo 'abcd-Regex1
BlaBlaBla
abcd-Regex2' | awk '/Regex2/{e=0}{if(e){print}}/Regex1/{e=1}'

BlaBlaBla

It basically uses an echo flag e, with the commands below executed in sequence for each line:

  • /Regex2/{e=0} turns echo off when terminating line found.
  • {if(e){print}} prints line if echo is on.
  • /Regex1/{e=1} turns echo on when initialising line found.

If you must use only sed, there is a way you can do it by passing it through another sed to delete the start and end lines:

pax> echo 'asdf
abcd-Regex1
BlaBlaBla
abcd-Regex2' | sed -n '/Regex1/,/Regex2/p' | sed -e '/Regex1/d' -e '/Regex2/d'

BlaBlaBla
paxdiablo
Thanks for the tip, but just out of curiosity: is there a way to do it whit the 'sed' command?
3sdmx
Not that I know of. That doesn't mean it _can't_ be done, just that _I_ don't know how to. And, given that it's pretty unusual to find a system with `sed` but no `awk`, I'd rather just use the tool more suited for the job.
paxdiablo
Thanks anyway, I'll keep searching :)
3sdmx
@3sdmx, there _is_ a `sed`-only solution if you're interested (or don't have `awk` for some reason), see the update.
paxdiablo
Works now, thanks for your answer!
3sdmx