title: bash, sed, awk: extracting lines within a range
body: <p>How can I get sed to extract the lines between two patterns, write that data to a file, and then extract the lines between the next range and write that text to another file? For example given the following input:</p>
  
  <pre><code>pattern_a
  line1
  line2
  line3
  pattern_b
  pattern_a
  line4
  line5
  line6
  pattern_b
  </code></pre>
  
  <p>I want line1 line2 and line3 to appear in one file and line4 line5 and line6 to appear in another file. I can't see a way of doing this without using a loop and maintaining some  state between iterations of the loop where the state tells you where sed must start start search to looking for the start pattern (pattern_a) again.</p>
  
  <p>For example, in bash-like psuedocode:</p>
  
  <pre><code>while not done
    if [[ first ]]; then
      sed -n -e '/pattern_a/,/pattern_b/p' &gt; $filename
    else
      sed -n -e '$linenumber,/pattern_b/p' &gt; $filename
    fi
    linenumber = last_matched_line
    filename = new_filename
  </code></pre>
  
  <p>Is there a nifty way of doing this using sed? Or would awk be better?</p>