简体   繁体   中英

Perl simple one-liner used to add header to a file doesn't work when input file is empty

We have in code one-liner used to add header to file. It looks like

perl -pi -e 'print "name, function, group\n" if $. == 1' CSV_FILE_NAME

Everything is fine except when CSV_FILE_NAME is empty then no header is added to CSV_FILE_NAME. So CSV_FILE_NAME after this command is still empty.

Bartosz,

This one-liner won't work on empty files because actually it looks this way:

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 $_;
}

When readline() tries to read from an empty file, it immediately hits eof (end of file) and the while loop ends right away. So, whatever workarounds one may try, for example placing a call to system() into the else{ } block:

perl -i -pe 'if ($.==1) { print "1, 2, 3\n" } else { system("echo 1, 2, 3 > test.txt") }' test.txt 

this block won't have the chance to be executed:

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 $_;
}

One solution is "to prime" empty files with something, making them non-empty. This script enters a new line into every empty file:

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: $!";
  }
}

After you have run this script on your empty files, you can apply on them your one-liner and it will work as expected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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