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
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 = ();
}
}
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With