-4

I have a pipe-delimited file named old.txt that looks like this:

Data1|Data2|Data3|Data4|Data5 
Data1|Data2|Data3|Data4|Data5
Data1|Data2|Data3|Data4|Data5

I need to copy its contents to a new file, named new.txt, but with the second column removed:

Data1|Data3|Data4|Data5
Data1|Data3|Data4|Data5
Data1|Data3|Data4|Data5

How do I do this?

4

2 回答 2

3

这在使用时是微不足道的Text::CSV。这是一个示例脚本:

use strict;
use warnings;
use Text::CSV;

my $csv = Text::CSV->new({
        binary   => 1,
        eol      => $/,
        sep_char => "|",
    });
open my $in, "<", "old.txt" or die $!;

while (my $row = $csv->getline($in)) {
    splice @$row, 1, 1;                 # remove 2nd column
    $csv->print(*STDOUT, $row);         # print the rest
}

输出:

Data1|Data3|Data4|Data5
Data1|Data3|Data4|Data5
Data1|Data3|Data4|Data5
于 2013-07-07T18:15:01.393 回答
2

This should be pretty straight forward.

#!/usr/bin/perl

use warnings;
use strict;

use autodie;

open my $old_fh, "<", "old.txt";
open my $new_fh, ">", "new.txt";

while(my $line = <$old_fh>) {
    # @data should have a more meaningful name
    my @data = split /\|/, $line; 

    # remove the second element in the array. 
    splice @data, 1, 1;
    print $new_fh join ' | ', @data;
}

close $old_fh;
close $new_fh;
于 2013-07-07T17:59:21.070 回答