Raw Input Desired Output
1 cat chicken
2 bird dog apple
3 dog orange cat
4 cat juice coffee
5 cow milk dog
1 cat chicken
2 bird dog apple
3 dog orange cat
4 cat juice coffee
5 cow milk DOG
Script and Comments
Script1
[ 1] /PAT1/{
[ 2] :loop
[ 3] $!{
[ 4] N
[ 5] /PAT1[^\n]*$/{
[ 6] h
[ 7] s/\(.*\)\n.*/\1/
[ 8] p
[ 9] x
[10] s/.*\n//
[11] }
[12] b loop
[13] }
[14] s/\(.*\)PAT1/\1PAT2/
[15] }
Comments
  1. Flowchart:
  2. Step [6] thru [10] will be performed if the newly appended line contains PAT1.
  3. Step [7] will remove the last line of pattern space.
  4. Step [10] will remove all except the last line of pattern space.
  5. In Step [14], although pattern space may contain several lines, since ONLY the first line contains PAT1 (note that it's possible that there are more than one PAT1 in that line), Step [13] can be used to replace the last occurrence of PAT1.