sed '$d' $file;
使用此命令似乎不起作用,因为$
是Perl中的保留符号。
答案 0 :(得分:5)
不知道为什么要将sed
用于Perl。 Perl本身有标准模块来删除文件中的最后一行。
使用标准(自v5.8起)Tie::File
模块并删除绑定数组中的最后一个元素:
use Tie::File;
tie @lines, Tie::File, $file or die "can't update $file: $!";
delete $lines[-1];
答案 1 :(得分:3)
最接近的语法似乎是:
perl -ne 'print unless eof()'
这将像sed
一样,即:无需将整个文件读入内存,并且可以使用 FIFO ,如STDIN
。
请参阅:
perl -ne 'print unless eof()' < <(seq 1 3)
1
2
或者也许:
perl -pe '$_=undef if eof()' < <(seq 1 3)
1
2
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)
将呈现:
Something special with 1
2
3
4
Other speciality with 5
perl -pe 's/^/Something... / if$.==1||eof' < <(seq 1 5)
将呈现:
Something... 1
2
3
4
Something... 5
试试这个:
perl -pe 'BEGIN{$s=join"|",qw|1 3 7 21|;};
if ($.=~/^($s)$/||eof){s/^/---/}else{s/$/.../}' < <(seq 1 22)
......类似于sed
命令:
sed '1ba;3ba;7ba;21ba;$ba;s/$/.../;bb;:a;s/^/---/;:b' < <(seq 1 22)
#!/usr/bin/perl -w
use strict;
sub something {
chomp;
print "Something special with $_.\n";
}
$_=<>;
something;
while (<>) {
if (eof) { something; }
else { print; };
}
会给:
/tmp/script.pl < <(seq 1 5)
Something special with 1.
2
3
4
Something special with 5.
答案 2 :(得分:-1)
希望你正在尝试执行“sed”#39;从perl脚本中间命令。我建议不要使用这种方法,因为它只适用于非Windows系统。下面是一种perl方法,您只需处理第一行和最后一行,而不是花费精力删除文件内容。谢谢。
假设&#34; myfile.txt&#34;作为输入文件:
open (FH, "<", "myfile.txt") or die "Unable to open \"myfile.txt\": $! \n";
$i = 1;
while(<FH>){
next if ($i++ == 1 or eof);
# Process other lines
print "\nProcessing Line: $_";
}
close (FH);
print "\n";
1;
myfile.txt -
# First line
This is the beginning of comment free file.
Hope this is also the line to get processed!
# last line
结果 -
Processing Line: This is the beginning of comment free file.
Processing Line: Hope this is also the line to get processed!