Shell: insert a blank/new line two lines above pattern


Question

To add a blank line above every line that matches your regexp, you can use:

sed '/regexp/{x;p;x;}'

But I want to add a blank line, not one line above, but two lines above the line which matches my regexp.

The pattern I'll be matching is a postal code in the address line.

Here is a snippet of the text's formatting:

random info (belongs to previous business)
business name
business address

For example:

Languages Spoken: English
Arnold's Cove, Nfld (sub To Clarenville)
Nile Road, Arnolds Cove, NL, A0B1N0

I'd like to add a new line above the business name:

Languages Spoken: English

Arnold's Cove, Nfld (sub To Clarenville)
Nile Road, Arnolds Cove, NL, A0B1N0

1
6
1/4/2014 9:27:33 PM

Accepted Answer

Something a bit like your original approach in sed:

sed '/regexp/i\

$H
x'

The basic idea is to print everything delayed by one line (xchange the hold and pattern spaces - printing is implicit). That needs to be done because until we check whether the next line matches the regexp we don't know whether to insert a newline or not.

(The $H there is just a trick to make the last line print. It appends the last line into the hold buffer so that the final implicit print command outputs it too.)

5
4/16/2009 11:00:02 PM

More readable Perl, and handles multiple files sanely.

#!/usr/bin/env perl
use constant LINES => 2;
my @buffer = ();
while (<>) {
    /pattern/ and unshift @buffer, "\n";
    push @buffer, $_;
    print splice @buffer, 0, -LINES;
}
continue {
    if (eof(ARGV)) {
        print @buffer;
        @buffer = ();
    }
}

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon