简体   繁体   English

Perl使用unix命令将文件分成几列

[英]Perl split file into columns with unix command

I have a file with various columns separated by tabs. 我有一个文件,其中各列用制表符分隔。 I' trying to invoke an unix command in perl but it gives me an error ever time 我试图在perl中调用unix命令,但是每次都给我一个错误

use strict;
use warnings;


system ("awk -F '\t' '{print $1}' file.txt > first_field.tmp");

Single quote your system command: 单引号您的system命令:

system(q{awk -F '\t' '{print $1}' file.txt > first_field.tmp});

Or without the need for an external resource: 或不需要外部资源:

use strict;
use warnings;
use autodie;

{
    local @ARGV = 'file.txt';
    open my $fh, '>', 'first_field.tmp';
    while (<>) {
        chomp;
        my @F = split "\t";
        $fh->print("$F[0]\n");
    }
}

You have a tab-separated value file. 您有一个制表符分隔的值文件。 What's wrong with Text::CSV in tab-separated mode then? 那么,制表符分隔模式下的Text::CSV有什么问题? No need to invoke awk for something like this. 无需为此类调用awk

Because you are using double quotes " " around your command, Perl is trying to interpolate the value of $1 . 因为您在命令周围使用双引号" " ,所以Perl试图对$1的值进行插值。 You need to escape it: 您需要对其进行转义:

system ("awk -F '\t' '{print \$1}' file.txt > first_field.tmp");

Or you could use ' quotes, which don't interpolate: 或者,您可以使用不插入的'引号:

system ('awk -F "\t" "{print $1}" file.txt > first_field.tmp');

...or qx : ...或qx

qx/awk -F '\t' '{print \$1}' file.txt > first_field.tmp/;

Seeing as you're such a big fan of Perl, I would recommend checking out the documentation regarding the various types of quotes and quote-like operators . 既然您是Perl的忠实拥护者,我建议您查看有关各种类型的引号和类似引号的运算符的文档。

Obviously this is the kind of thing that Perl eats for breakfast, so if you're looking for a native solution I would recommend using what @Miller has posted, or one of the million other ways you could do the same thing in Perl. 显然,这是Perl在早餐时吃的东西,因此,如果您正在寻找本机解决方案,我建议您使用@Miller发布的内容,或者您​​可以在Perl中完成相同操作的数百万种方法中的一种。

An alternative version using the Text::CSV package as suggested by @LeoNerd: @LeoNerd建议使用Text::CSV包的替代版本:

use strict;
use warnings;

{
    use Text::CSV;

    my $csv = Text::CSV->new ( { sep_char => "\t" } )
                    or die "Cannot use CSV: ".Text::CSV->error_diag ();

    open my $fh, "<", "file.txt" or die "file.txt: $!";
    open my $out, ">", "first_field.tmp" or die "first_field.tmp: $!";
    while ( my $row = $csv->getline( $fh ) ) {
        $out->print("$row->[0]\n");
    }
    $csv->eof or $csv->error_diag();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM