Description
Given a file consisting of two parts:
  • The first part begins with a line of the form table and ends with a line of the formend_table. Each line between them is treated as a key-value pair, separated by one or more blanks.
  • Every line of the other part consists of several fields separated by one or more blanks.
We want to treat as a key the last field of every line of the second part and replace it with the associated value.
Raw Input Desired Output
table
1 Linux
2 AIX
4 Solaris
11 VMS 
end_table
1  5  7  3  1
1  2  6  5  2
2  9 11  6  4
9 13 15 11  1
3  5  8 13  11
1  5  7  3  Linux
1  2  6  5  AIX
2  9 11  6  Solaris
9 13 15 11  Linux
3  5  8 13  VMS
Script and Comments
Script1
[ 1] /^table$/,/^end_table$/{
[ 2] /^(end_)?table$/!H
[ 3] d
[ 4] }
[ 5] G
[ 6] s/([^ \n]+)\n(\n[^ \n]+ +[^\n]+)*\n\1 +([^\n]+).*/\3/
Comments
  1. The `-r' option of GNU sed must be used to make sed interpret REs as EREs.
  2. Steps [1] thru [4] constitute a loop which will copy every key-value pair to the Hold Space. After processing the first part of the given datafile, the contents of the Hold Space are
    \n1 Linux\n2 AIX\n4 Solaris\n11 VMS.
  3. For lines of the second part, Step [4] will append all key-value pairs (kept in the Hold Space) to the Pattern Space and Step [5] will replace the key with the associated value.