Bruc Walker
Bruc Walker

Reputation: 253

how to remove a blank line after removing an unwanted line in perl?

For example, I want to remove unwanted line with bbbb

aaaa
bbbb
cccc
dddd

I use the following perl regular expression to accomplish this.

$_ =~ s/bbbb//g;

The problem here is that a blank line is stays, for example

aaaa

cccc
dddd

I need to remove the unwanted text line and also the blank line.

Upvotes: 1

Views: 178

Answers (2)

Lucas
Lucas

Reputation: 14949

It seems to me that if you are reading this line by line you could just have your loop do this:

my @foo = (
    "aaaa\n",
    "bbbb\n",
    "cccc\n",
    "dddd\n" );

foreach my $line ( @foo ) {
    next if ( $line =~ /^bbbb$/ );

    # now do something with a valid line;
}

Upvotes: 1

larsks
larsks

Reputation: 311606

You could simply include the newline in your regular expression:

$_ =~ s/bbbb\n//g;

This will result in:

aaaa
cccc
dddd

Upvotes: 4

Related Questions