Description
In the following example, we want to prepend the contents of 'file2' before every line of 'file1' that ends with 2,3 or 5.
Raw Input Desired Output
file1:
line 1
line 2
line 3
line 4
line 5
file2: sample A sample B
line 1
sample A
sample B
line 2
sample A
sample B
line 3
line 4
sample A
sample B
line 5
Script and Comments
Script1
[ 1] 1!{
[ 2] x
[ 3] p
[ 4] x
[ 5] }
[ 6] h
[ 7] /[235]$/r file2
[ 8] d
Comments
  1. Command:'r file2' will not insert contents of file2 until
    • the end of script is reached,
    • a cycle is terminated, or
    • command 'N' or 'n' is performed
    therefore, if we want to prepend contents of file2 before a line, we have to run command 'r' in a cycle prior to that one printing the line.
  2. Pattern and Hold Space are abbreviated to PS, and HS, respectively.
  3. This script us HS to keep the line read in last cycle, and Step [2] thru [4] are used to print it.
  4. Command 'h' of Step [5] is used to save the current line to HS.
  5. If the current line ends with 2, 3, or 5, command:'r file2' will make sed print the contents of file2 at end of this cycle.
  6. Command 'd' of Step [8] will delete the contents of PS (that consists of the current line) and start a new cycle.
  7. To make this script print the last line,
    you can either append an empty line to the end of data file or
    sed '$G' file1 | sed -f this_script.