5

Consider the simplified file

AAA
BBB
CCC1
DDD
EEE
CCC2
DDD
FFF
GGG
CCC3
HHH

I can pick out the range EEE to FFF with

sed -n '/EEE/,/FFF/p'

Suppose though that I want to print any line containing C but only within the matching range. I can pipe the result from sed through grep

sed -n '/EEE/,/FFF/p' | grep 'C'

I could also do the range and match in a little awk script (or perl, python, etc.). But how would I do this using just one invocation of sed?

choroba
  • 45,735
  • 7
  • 84
  • 110
roaima
  • 107,089
  • 14
  • 139
  • 261
  • Pretty much a duplicate of [Pattern Search between specific lines and print line numbers](https://unix.stackexchange.com/q/178551/22142) if you remove the "line numbers" part. I'm sure there are better candidates out there... – don_crissti Sep 29 '18 at 12:36
  • @don_crissti looks that way doesn't it. But I couldn't find anything previous before asking. – roaima Sep 29 '18 at 16:26

2 Answers2

14

Use a block in which you tell sed to only print when it sees C:

sed -n '/EEE/,/FFF/{/C/p}'
choroba
  • 45,735
  • 7
  • 84
  • 110
4

You can try :

sed '/EEE/,/FFF/!d;/C/!d'
ctac_
  • 1,960
  • 1
  • 6
  • 14
  • I like this solution too. I haven't got my head around the idea of deleting lines I don't want (although that's perfectly reasonable in a stream editor), and actually not having the `-n` flag requiring `/p` has advantages. Thanks – roaima Sep 29 '18 at 17:37