-2

how can i remove the first line from my list of file , this is my code,

open my directory:

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);

open my file:

foreach my $val(@tab){


utf8::encode($val);

my $filename = $val;

open(my $in, '<:utf8', $filename) or die "Unable to open '$filename' for read: $!";

rename file

my $newfile = "$filename.new";

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

remove the first line

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;

the probem my new file is empty ! rename $newfile,$filename or die "unable to rename '$newfile' to '$filename': $!"; }

It seems true but the result is an empty file.

halfer
  • 19,824
  • 17
  • 99
  • 186
rim
  • 39
  • 4
  • http://stackoverflow.com/questions/2112469/delete-specific-line-numbers-from-a-text-file-using-sed – ViFI Mar 30 '17 at 20:56
  • There should be a way to invoke command from inside perl. With that all you need to do is `sed -e '1d' filename.txt` – ViFI Mar 30 '17 at 20:59
  • because i have a lot of file how can i change sed -e '1d' filename.txt to remove the first line from many file in the same time (directory of file) – rim Mar 30 '17 at 21:03
  • You should preprend `$filename` with `$directory` before reading from it: `$filename = $directory . '/' . $filename`. Also it is not necessary to encode the filename before opening it. See [this topic of SO docs](http://stackoverflow.com/documentation/perl/4375/unicode/15287/create-filenames#t=201703302112430306543) – Håkon Hægland Mar 30 '17 at 21:09
  • Also when printing the array back to file you should set `$, = "\n"` – Håkon Hægland Mar 30 '17 at 21:16

1 Answers1

2

The accepted pattern for doing this kind of thing is as follows:

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

In your case, we're using $. (the input line number variable) to skip over the first line.

Matt Jacob
  • 6,503
  • 2
  • 24
  • 27