Description
We want to perform a specific operation on lines range from the beginning of a file till the last line containing `PAT'. In this example, the specific operation is replacing `this' with `that'.
Raw Input Desired Output
..
PAT
..replace this.
..replace this.
PAT
..replace this.
..replace this.
PAT reeplace this.
..keep this.
..keep this.
..
PAT
..replace that.
..replace that.
PAT
..replace that.
..replace that.
PAT replace that.
..keep this.
..keep this.
Script and Comments
Script1
[ 1] :loop
[ 2] /PAT/!{
[ 3] $!N
[ 4] $!b loop
[ 5] }
[ 6] /PAT/s/this/that/g
Comments
  1. The Patten Space is abbreviated to PS.
  2. Steps [1] thru [5] constitute a loop which will append lines from datafile to PS until
    • a line containing `PAT' or
    • the end of file is reached.
  3. Step [6] is reached only when
    • Exact one line in PS contains `PAT'. Besides, lines in PS are not behind the last line containing `PAT' of the file.
      Therefore, the specific operation must be performed on them.
    • The last line of the datafile is reached. No lines in PS contain `PAT', i.e., lines in PS are behind the last line containing `PAT' of the file.
      Therefore, the operation must NOT be performed.