使用perl删除文件的最后一行

Iys*_*rya -2 unix perl

sed '$d' $file; 
Run Code Online (Sandbox Code Playgroud)

使用此命令似乎不起作用,因为$Perl中的保留符号.

ser*_*sat 5

不知道你为什么使用sedPerl.Perl本身有标准模块来删除文件中的最后一行.

使用标准(从v5.8开始)Tie::File模块并删除绑定数组中的最后一个元素:

use Tie::File;

tie @lines, Tie::File, $file or die "can't update $file: $!";
delete $lines[-1];
Run Code Online (Sandbox Code Playgroud)


F. *_*uri 5

仅最后一行

最接近的语法似乎是:

perl -ne 'print unless eof()'
Run Code Online (Sandbox Code Playgroud)

这将像sed,即:无需将整个文件读入内存,并且可以像FIFO一样工作STDIN

看到:

perl -ne 'print unless eof()' < <(seq 1 3)
1
2
Run Code Online (Sandbox Code Playgroud)

或许:

perl -pe '$_=undef if eof()' < <(seq 1 3)
1
2
Run Code Online (Sandbox Code Playgroud)

第一行和最后一行

perl -pe '
    BEGIN {
        chomp(my $first= <>);
        print "Something special with $first\n";
    };
    do {
        chomp;
        print "Other speciality with $_\n";
        undef $_;
    } if eof();
  ' < <(seq 1 5)
Run Code Online (Sandbox Code Playgroud)

将呈现:

Something special with 1
2
3
4
Other speciality with 5
Run Code Online (Sandbox Code Playgroud)

最短:第一行和最后一行:

perl -pe 's/^/Something... / if$.==1||eof' < <(seq 1 5)
Run Code Online (Sandbox Code Playgroud)

将呈现:

Something... 1
2
3
4
Something... 5
Run Code Online (Sandbox Code Playgroud)

尝试这个:

perl -pe 'BEGIN{$s=join"|",qw|1 3 7 21|;};
          if ($.=~/^($s)$/||eof){s/^/---/}else{s/$/.../}' < <(seq 1 22)
Run Code Online (Sandbox Code Playgroud)

...类似sed命令:

sed '1ba;3ba;7ba;21ba;$ba;s/$/.../;bb;:a;s/^/---/;:b' < <(seq 1 22)
Run Code Online (Sandbox Code Playgroud)

在脚本文件中:

#!/usr/bin/perl -w

use strict;

sub something {
    chomp;
    print "Something special with $_.\n";
}

$_=<>;
something;

while (<>)  {
    if (eof) { something; }
    else { print; };
}
Run Code Online (Sandbox Code Playgroud)

会给:

/tmp/script.pl < <(seq 1 5)
Something special with 1.
2
3
4
Something special with 5.
Run Code Online (Sandbox Code Playgroud)