0

I am trying to print text after a pattern match till it matches other pattern several times in a file. I have tried to modify the script given here but failed to do it. eg. The content of file1.txt

example text
more example
pattern1
important text
very important 
need this too
pattern2
i dont require this
junk text
more junk
pattern1
important text
very important 
need this too
pattern2
junk

Expected Output

pattern1
important text
very important 
need this too
pattern1
important text
very important 
need this too

can anyone suggest the edit?

Thanks.

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255

1 Answers1

1

Matching between lines between patterns, including either boundary, is a standard range selector in sed:

sed -n -e '/pattern1/,/pattern2/p' example.txt

Depending on how efficiency-critical you are (how big the files are), I'd probably be lazy and use a second pass to delete the pattern2 markers:

cat example.txt \
| sed -n -e '/pattern1/,/pattern2/p' \
| sed    -e '/pattern2/d'

(Yes, this is a useless use of cat, because I prefer the readability of chaining several piping filters over the performance loss, and I'm not sure right now if < example.txt | sed ... | sed ... is mandated by POSIX or just an extension that happens to be present in bash and zsh.)