开发者

read input file, match and remove data and write remaining lines to a new file

开发者 https://www.devze.com 2023-04-13 10:02 出处:网络
I am stuck trying to get this to write out the contents of the file. What I am trying to do is open an input file, filter out/remove the matched line and write to a new file. Can someone show me how t

I am stuck trying to get this to write out the contents of the file. What I am trying to do is open an input file, filter out/remove the matched line and write to a new file. Can someone show me how to do this properly? Thanks.

use strict;
use warnings;
use Text::CSV_XS;

my $csv = Text::CSV_XS->new ({ binary => 1 }) or
     die "Cannot use CSV: ".Text::CSV_XS->error_diag ();
open my $fh, "<:encoding(UTF-16LE)", "InputFile.txt" or die "cannot open file: $!";

my @rows;
while (my $row = $csv->getline ($fh)) {
    my @lines;
    shift @lines if $row->[0] 开发者_如何学JAVA=~ m/Global/;

    my $newfile = "NewFile.txt";

    open(my $newfh, '>', $newfile) or die "Can't open";
    print $newfh @lines;

    }
$csv->eof or $csv->error_diag ();
close $fh;


Open the output file outside of the loop. As you read each line, decide if you want to keep it. If yes, write to output file. If not, don't do anything.

Something like the following (untested):

use strict;
use warnings;
use Text::CSV_XS;

my ($input_file, $output_file) = qw(InputFile.txt NewFile.txt);

my $csv = Text::CSV_XS->new ({ binary => 1 })
    or die sprintf("Cannot use CSV: %s\n", Text::CSV_XS->error_diag);

open my $infh, "<:encoding(UTF-16LE)", $input_file
    or die "Cannot open '$input_file': $!";

open my $outfh, '>', $output_file
    or die "Cannot open '$output_file': $!";

while (my $row = $csv->getline($infh)) {
    next if $row->[0] =~ m/Global/;
    unless ( $csv->print($outfh, $row) ) {
        die sprintf("Error writing to '%s': %s",
            $output_file,
            $csv->error_diag
        );
    }
}

close $outfh
    or die "Cannot close '$output_file': $!";

close $infh
    or die "Cannot close '$input_file': $!";

$csv->eof
    or die "Processing of '$input_file' terminated prematurely";
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号