Perl 从我的目录中删除第一行
如何从文件列表中删除第一行,这是我的代码 打开我的目录:Perl 从我的目录中删除第一行,perl,Perl,如何从文件列表中删除第一行,这是我的代码 打开我的目录: use strict; use warnings; use utf8; use Encode; use Encode::Guess; use Devel::Peek; my $new_directory = '/home/lenovo/corpus'; my $directory = '/home/lenovo/corpus'; open( my $FhResultat, '>:encoding(UTF-8)', $Fich
use strict;
use warnings;
use utf8;
use Encode;
use Encode::Guess;
use Devel::Peek;
my $new_directory = '/home/lenovo/corpus';
my $directory = '/home/lenovo/corpus';
open( my $FhResultat, '>:encoding(UTF-8)', $FichierResulat );
my $dir = '/home/corpus';
opendir (DIR, $directory) or die $!;
my @tab;
while (my $file = readdir(DIR)) {
next if ($file eq "." or $file eq ".." );
#print "$file\n";
my $filename_read = decode('utf8', $file);
#print $FichierResulat "$file\n";
push @tab, "$filename_read";
}
closedir(DIR);
打开我的文件:
foreach my $val(@tab){
utf8::encode($val);
my $filename = $val;
open(my $in, '<:utf8', $filename) or die "Unable to open '$filename' for read: $!";
删除第一行
my @ins = <$in>; # read the contents into an array
chomp @ins;
shift @ins; # remove the first element from the array
print $out @ins;
close($in);
close $out;
my@ins=;#将内容读入数组
chomp@ins;
shift@ins;#从数组中删除第一个元素
打印$out@ins;
收盘价(美元);
收尾美元;
问题是我的新文件是空的!
重命名$newfile、$filename或“无法将“$newfile”重命名为“$filename”:$!”;
}
这似乎是真的,但结果是一个空文件。执行此类操作的公认模式如下:
use strict;
use warnings;
my $old_file = '/path/to/old/file.txt';
my $new_file = '/path/to/new/file.txt';
open(my $old, '<', $old_file) or die $!;
open(my $new, '>', $new_file) or die $!;
while (<$old>) {
next if $. == 1;
print $new $_;
}
close($old) or die $!;
close($new) or die $!;
rename($old_file, "$old_file.bak") or die $!;
rename($new_file, $old_file) or die $!;
使用严格;
使用警告;
my$old_file='/path/to/old/file.txt';
my$new_file='/path/to/new/file.txt';
打开(我的$old,,$new_文件)或死亡$!;
而(){
如果$.==1,则为下一步;
打印$new$;
}
关闭($旧)或死亡($!;
关闭($新)或死亡$!;
重命名($old_file,“$old_file.bak”)或die$!;
重命名($new_file,$old_file)或die$!;
在您的例子中,我们使用
$。
(the)跳过第一行。应该有一种从perl内部调用命令的方法。有了这些,你所需要做的就是sed-e'1d'filename.txt
,因为我有很多文件,如何更改sed-e'1d'filename.txt以同时删除多个文件的第一行(文件目录)在从中读取之前,您应该先使用$directory
预加载$filename
:$filename=$directory.'/'$文件名
。此外,在打开文件名之前,无需对其进行编码。另请参见将阵列打印回文件时,您应设置$,=“\n”
use strict;
use warnings;
my $old_file = '/path/to/old/file.txt';
my $new_file = '/path/to/new/file.txt';
open(my $old, '<', $old_file) or die $!;
open(my $new, '>', $new_file) or die $!;
while (<$old>) {
next if $. == 1;
print $new $_;
}
close($old) or die $!;
close($new) or die $!;
rename($old_file, "$old_file.bak") or die $!;
rename($new_file, $old_file) or die $!;