【问题标题】:Remove the first line from my directory从我的目录中删除第一行
【发布时间】:2017-08-24 23:37:10
【问题描述】:

如何从我的文件列表中删除第一行,这是我的代码,

打开我的目录:

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 $newfile = "$filename.new";

open(my $out, '>:utf8', $newfile) or die "Unable to open '$newfile' for write: $!";

删除第一行

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;

探测我的新文件是空的! rename $newfile,$filename or die "无法将 '$newfile' 重命名为 '$filename': $!"; }

这似乎是真的,但结果是一个空文件。

【问题讨论】:

  • 应该有一种从 perl 内部调用命令的方法。有了这个,你需要做的就是sed -e '1d' filename.txt
  • 因为我有很多文件如何更改 sed -e '1d' filename.txt 以同时从多个文件中删除第一行(文件目录)
  • 在阅读之前,您应该在 $filename 前面加上 $directory$filename = $directory . '/' . $filename。此外,在打开文件之前也没有必要对文件名进行编码。见this topic of SO docs
  • 另外,当将数组打印回文件时,您应该设置$, = "\n"

标签: perl


【解决方案1】:

做这种事情的公认模式如下:

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 $!;

在您的情况下,我们使用$.input line number variable)跳过第一行。

【讨论】:

    猜你喜欢
    • 2021-01-30
    • 2015-07-19
    • 1970-01-01
    • 2011-07-15
    • 1970-01-01
    • 2019-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多