【问题标题】:Script to remove first line from all the text files in a directory从目录中的所有文本文件中删除第一行的脚本
【发布时间】:2012-02-29 23:06:27
【问题描述】:

我正在尝试编写一个 Perl 脚本,该脚本读取目录中的所有文本文件,并将除第一行之外的所有行写入单独的文件。如果有 3 个文件,我希望脚本读取所有这 3 个文件并写入 3 个具有相同行的新文件,但第一个文件除外。这就是我写的.. 但是当我尝试运行脚本时,它执行得很好,没有错误,但没有做它应该做的工作。有人可以看看吗?

opendir (DIR, "dir\\") or die "$!";
my @files = grep {/*?\.txt/}  readdir DIR;
close DIR;
my $count=0;
my $lc;
foreach my $file (@files) {
   $count++;
   open(FH,"dir\\$file") or die "$!";
   $str="dir\\example_".$count.".txt";
   open(FH2,">$str");
   $lc=0;
   while($line = <FH>){
        if($lc!=0){
            print FH2 $line;
        }
        $lc++;
    }
   close(FH);
   close(FH2);
}

第二个文件不存在,应该是脚本创建的。

【问题讨论】:

  • 它对我有用,但我必须在第二行引用*。你真的有一个名为dir的目录吗,你的路径分隔符是`\`吗?
  • @EmilioSilva- 谢谢,这就是问题所在。

标签: perl


【解决方案1】:

尝试更改这些行

opendir (DIR, "dir\\") or die "$!";
...
close DIR;

opendir (DIR, "dir") or die "$!";
...
closedir DIR;

我尝试在本地运行您的代码,我遇到的唯一两个问题是包含尾部斜杠的目录名称和尝试在 dirhandle 上使用文件句柄 close() 函数。

【讨论】:

  • 感谢您的关注,其他问题未引用 *。
【解决方案2】:

如果你有文件列表...

foreach my $file ( @files ) {
  open my $infile , '<' , "dir/$file" or die "$!" ;
  open my $outfile , '>' , "dir/example_" . ++${counter} . '.txt' or die "$!" ;
  <$infile>; # Skip first line.
  while( <$infile> ) {
    print $outfile $_ ;
  }
}

词法文件句柄将在超出范围时自动关闭。

【讨论】:

    【解决方案3】:

    不知道你为什么在这里使用 $count,因为这只会变成一个文件列表,例如:

    01.txt
    bob.txt
    alice.txt
    02.txt
    

    进入:

    01_1.txt
    bob_2.txt
    alice_3.txt
    02_4.txt
    

    请记住,@files 没有被排序,因此它将按照文件在目录表中存在的顺序返回。如果您要删除并重新创建文件 01.txt,它将被移动到列表的末尾,重新排序整个集合:

    bob_1.txt
    alice_2.txt
    02_3.txt
    01_4.txt
    

    由于这并不是您最初问题的一部分,因此这正是您要求做的:

    #!/usr/bin/perl
    while(<*.txt>) { # for every file in the *.txt glob from the current directory
        open(IN, $_) or die ("Cannot open $_: $!"); # open file for reading
        my @in = <IN>; # read the contents into an array
        close(IN); # close the file handle
        shift @in; # remove the first element from the array
    
        open(OUT, ">$_.new") or die ("Cannot open $_.new: $!"); # open file for writing
        print OUT @in; # write the contents of the array to the file
        close(OUT); # close the file handle
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-04
      • 2016-02-06
      • 1970-01-01
      • 2015-11-22
      • 2015-11-27
      • 2017-10-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多