Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sed script to remove first two lines of file if they are empty

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!

like image 662
Component 10 Avatar asked Dec 09 '22 02:12

Component 10


2 Answers

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.

like image 53
cjm Avatar answered Apr 19 '23 23:04

cjm


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 <>;
like image 43
Benoit Avatar answered Apr 19 '23 22:04

Benoit