26 June 2013

Sed two-line match and replace using pattern and hold space

Sed is a line-oriented text processing tool, so to match and replace a two-line pattern requires accumulating lines in the hold space then testing if those lines should be changed. Today, I had a chance to use this feature to remap some Hyperion Financial Management (HFM) journal files.

HFM journal files have the following heading format. The scenario and year lines only appear once in a journal file.


The task was to remap journal files for only one scenario and year to another scenario. Below is the resulting sed script.

# x = Exchange Pattern and Hold
# H = Hold = Hold + \n + pattern
/!Scenario=/ {
/!Year=2010/ {

Not obvious: In the first rule, there is no output because the pattern space is empty. The second rule always outputs the scenario and year lines regardless of whether they have been changed.