[英]Perl simple one-liner used to add header to a file doesn't work when input file is empty
我們在代碼中使用單行代碼將 header 添加到文件中。 看起來像
perl -pi -e 'print "name, function, group\n" if $. == 1' CSV_FILE_NAME
一切都很好,除非 CSV_FILE_NAME 為空,然后沒有 header 被添加到 CSV_FILE_NAME。 所以這個命令之后的 CSV_FILE_NAME 仍然是空的。
巴托什,
這個單行代碼不適用於空文件,因為實際上它看起來是這樣的:
perl -MO=Deparse -i -pe 'print "name, function, group\n" if $. == 1' test.txt
BEGIN { $^I = ""; }
LINE: while (defined($_ = readline ARGV)) {
print "name, function, group\n" if $. == 1;
}
continue {
die "-p destination: $!\n" unless print $_;
}
當readline()
嘗試從一個空文件中讀取時,它會立即命中eof
(文件結尾)並且while
循環立即結束。 因此,無論嘗試什么變通方法,例如將對system()
的調用放入else{ }
塊:
perl -i -pe 'if ($.==1) { print "1, 2, 3\n" } else { system("echo 1, 2, 3 > test.txt") }' test.txt
這個塊將沒有機會被執行:
BEGIN { $^I = ""; }
LINE: while (defined($_ = readline ARGV)) {
if ($. == 1) {
print "1, 2, 3\n";
}
else {
system 'echo 1, 2, 3 > test.txt';
}
}
continue {
die "-p destination: $!\n" unless print $_;
}
一種解決方案是用一些東西“填充”空文件,使它們不為空。 此腳本在每個空文件中輸入一個新行:
use strict;
use warnings;
foreach my $file (@ARGV) # for each file on the command line: primer.pl file1 file2 file3...
{
if (-z $file) # if the file has zero size
{
open my $fh, ">>", $file or die "$0: Cannot open $file: $!";
print $fh "\n";
close $fh or die "$0: Cannot close $file: $!";
}
}
在您的空文件上運行此腳本后,您可以在它們上應用您的單線,它會按預期工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.