user1954970
user1954970

Reputation: 409

How to delete particular lines in perl?

I have a file as below, i want to search for this line test name="" and delete next 4 lines including the first one test name="".

<test name="FT S_CREATE_DELETE_JOB">
<class name="11 .98. FT S_CREATE_DELETE_JOB">
COMPLETED
<test name="">
<class name="11.98.">
</class>
</test>

Upvotes: 0

Views: 210

Answers (1)

David W.
David W.

Reputation: 107040

In most languages, you don't manipulate files directly. Instead, you open a second file, write your results there, and then rename the second file to the first and delete the original:

use strict;
use warnings;
use autodie;

open my $input_fh, "<", "input.txt";
open my $output_fh, ">", "output.txt";
while ( my $line = <$input_fh> ) {
    chomp;
    last if $line eq '<test name="">';
    print {$output_fh} "$line\n";
}
close $input_fh;
close $output_fh;
unlink "input.txt";
rename "output.txt", "input.txt";

This is pretty basic stuff, so I suspect you don't know Perl. Maybe it's time to learn it.

Upvotes: 2

Related Questions