in reply to Remove multiple lines in file if pattern found based on array element, in perl

Perl's /i runtime flag does not apply exactly to your situation, but it is a good idea to imitate its file renaming etc.

You can test for all the elements of the array at once.

my $rprow = join '|', @remove_power_list; $rprow = qr/(?:$rprow)/;

Use $rprow as before, but the loop on @remove_power_list is no longer needed.

Bill
  • Comment on Re: Remove multiple lines in file if pattern found based on array element, in perl
  • Download Code

Replies are listed 'Best First'.
Re^2: Remove multiple lines in file if pattern found based on array element, in perl
by MatD (Initiate) on Nov 07, 2014 at 21:55 UTC

    Thank you Bill for answer. It works, but was not able to remove the empty comments along with that.

    #######Remove power using remove_power_list ########### my $outfile; my $arr_content; my $rprow = join '|', @remove_power_list; $rprow = qr/(?:$rprow)/; if (@remove_power_list != 0) { my $bf_content; open $bf_content, '<', $bf_bind; ###bf_bind is file in bigger +for loop my @bf_array = <$bf_content>; close $bf_content; open $outfile, '>', $bf_bind; for $arr_content (@bf_array){ next if (@arr_content=~/$rprow/); print $outfile $arr_content; } close $outfile; }

    I think if there is any other string (not in my intended lines) matching with the element (for example "vcchg") from @remove_power_list array, should it remove those lines too. I tested some cases by putting string like: "set intfcInstName vcchg", outside or inside my unintended block and it doesn't delete, which is good. But, I don't know why.