I'm trying to write a fairly concise sed script to remove the first two lines of a file only if they are empty, so the following file:
> cat myfile.in
Line 3
Line 5
Would result in a three line output file:
> cat myfile.out
Line 3
Line 5
This involves combining line ranges and pattern matching and I just can't seem to find any examples of that. I'd also be intersted if anyone could suggest and equally (or more) consise Perl alternative. Many thanks.
Footnote
I should add that I tried 1,2{/^$/d}
which worked absolutely fine on Linux, but under AIX I got:
sed: 0602-404 Function 1,2{/^$/d} cannot be parsed.
and on Solaris I got:
sed: command garbled: 1,2{/^$/d}
Which is a blow because this code has to run on both AIX and Solaris, but not Linux! Shame!
Here's one way to do it in Perl:
perl -ne 'print if $. > 2 or $_ ne "\n"' <myfile.in >myfile.out
If you want to allow additional whitespace on your empty lines:
perl -ne 'print if $. > 2 or /\S/' <myfile.in >myfile.out
This next version does something a bit different. It removes only initial blank lines (up to 2). If the first line is not blank, but the second is, both lines will be printed. (I thought of it before you replied to my comment, and I like it, and the next person who happens across this question might have different requirements.)
perl -ne 'print if $started ||= $. > 2 || /\S/'
The $started ||=
means that once printing starts, it won't stop.
Not a perl monk, but I would do this in Perl (probably there is a better way):
$_ = <> or exit 0; print unless /^\s*$/;
$_ = <> or exit 0; print unless /^\s*$/;
print while <>;
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