![](/img/trans.png)
[英]How can I split a file into a given number of parts in Perl? (On Unix)
[英]Perl split file into columns with unix command
我有一個文件,其中各列用制表符分隔。 我試圖在perl中調用unix命令,但是每次都給我一個錯誤
use strict;
use warnings;
system ("awk -F '\t' '{print $1}' file.txt > first_field.tmp");
單引號您的system
命令:
system(q{awk -F '\t' '{print $1}' file.txt > first_field.tmp});
或不需要外部資源:
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");
}
}
您有一個制表符分隔的值文件。 那么,制表符分隔模式下的Text::CSV
有什么問題? 無需為此類調用awk
。
因為您在命令周圍使用雙引號" "
,所以Perl試圖對$1
的值進行插值。 您需要對其進行轉義:
system ("awk -F '\t' '{print \$1}' file.txt > first_field.tmp");
或者,您可以使用不插入的'
引號:
system ('awk -F "\t" "{print $1}" file.txt > first_field.tmp');
...或qx
:
qx/awk -F '\t' '{print \$1}' file.txt > first_field.tmp/;
既然您是Perl的忠實擁護者,我建議您查看有關各種類型的引號和類似引號的運算符的文檔。
顯然,這是Perl在早餐時吃的東西,因此,如果您正在尋找本機解決方案,我建議您使用@Miller發布的內容,或者您可以在Perl中完成相同操作的數百萬種方法中的一種。
@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.