Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 221
Dennis Avatar asked Apr 16 '09 18:04

Dennis


2 Answers

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 = ();
    }
}
like image 179
ephemient Avatar answered Nov 14 '22 23:11

ephemient


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.)

like image 26
Jukka Matilainen Avatar answered Nov 14 '22 21:11

Jukka Matilainen