【问题标题】:Remove first line of a file using perl -pe使用 perl -pe 删除文件的第一行
【发布时间】:2014-04-22 20:08:31
【问题描述】:

我正在尝试使用 perl -pe 而不是 system & sed -i 来删除输出文件“bss_concurrent_calls.txt”的第一行。我使用的服务器是 solaris 9(实际上它不识别“sed -i”)

open my $file_in, "<", "/export/home/cassi/4.1-15_HPBX/cfg/LicenseCounters.log" or die($!);

open my $file_out,   '>', 'bss_concurrent_calls.txt' or die $!;

while( <$file_in> ) {
    my @columns = split /\s+/, $_;
    print $file_out "$columns[0]\t$columns[2]\n";

}
system('sed "1d" bss_concurrent_calls.txt');
close $file_in;
close $file_out or die $!;

【问题讨论】:

  • 调用系统的更好方法是使用参数列表:这样可以避免产生 /bin/sh 来调用命令:system 'sed', '1d', 'bss_concurrent_calls.txt';
  • 为什么不简单地tail -n +2 bss_concurrent_calls.txt

标签: perl sed


【解决方案1】:

这里(或其他任何地方)无需从 Perl 调用 sed。

perl -ane 'print "$F[0]\t$F[2]\n" unless $. == 1' \ 
    < /export/.../LicenseCounters.log > bss_concurrent_calls.txt

【讨论】:

    【解决方案2】:

    我喜欢@choroba 的回答,但如果你想保持你的程序结构:

    use autodie;
    open my $file_in,  '<', '/export/home/cassi/4.1-15_HPBX/cfg/LicenseCounters.log';
    open my $file_out, '>', 'bss_concurrent_calls.txt';
    
    my $line1 = <$file_in>;  # read the first line
    while (<$file_in>) {
        print $file_out join("\t", (split)[0,2]), "\n";
    }
    
    close $file_in;
    close $file_out;
    

    【讨论】:

    • 只要scalar &lt;$line_in&gt; 就可以了。无需声明变量
    【解决方案3】:
    while( <$file_in> ) {
        next unless $i++;
        my @columns = split /\s+/, $_;
        print $file_out "$columns[0]\t$columns[2]\n";
    
    }
    

    【讨论】:

    • @Oesor...您能否解释一下“下一个除非 $i++;”是在做?谢谢。
    • 跳过第一行。使用全局范围的 undef $i,第一次通过循环 $i++ 返回 0,然后将 $i 后增量为 1。由于 0 为假,代码转到下一行。下一次,它返回正整数,或 true,这意味着 next unless true 永远不会触发 next
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多