March archive

sed fanciness

Multi-line sed matching! This is easy if the pattern is only two lines. Sed line-based, so you have to issue a command to join the lines in sed's memory so you can match over the line boundaries. For example, if you want to match:

FOO BAR

First, we need to tell sed to join the lines with the N command, then we need to match on the pattern FOO\nBAR. To print the matching lines, we use the p command:

sed -n 'N; /FOO\nBAR/p' file

This works great if FOO happens to land on an even-numbered row, but fails otherwise. Why? sed only reads each line once, so it'll read line 1, then as a response to the N command read in line two............