alexeim
alexeim

Reputation: 7

File managing issues

im working on a simple script to rename & move files into a new directory. I can't seem to get it work properly, basically if the folder is already created it will moves the files into it only if the files are renamed, if the folder is already created but files need to be renamed it won't work it will just rename the files and give me an error because it won't be able to move the files. If the folder need to be created and files to be renamed it will create the folder and rename the files but it won't be able to move them. So i am a bit lost really..

https://i.sstatic.net/v8smp.jpg

I've been trying a lot of different way but it ends up not working or giving me the same result i think i am doing something wrong, heres my code :

use strict;
use warnings;
use File::Copy qw(mv);

my ($movie, $season, $cont) = @ARGV;

if (not defined $movie) {
    die "need a name as first argument\n";
}

if (defined $movie and defined $season and defined $cont) {

    print "\n\nProcessing $movie season $season with container .$cont :\n";

    my $npath = "Saison "."$season";
    my $exist = 0;
    my $num = 1;
    my $ind = 0;
    my $flast = undef;
    my $rpath = undef;
    my @files = glob("*.$cont");
    my @all = glob('*');

    foreach my $f (@files) {
        if ($f =~ m/e([0-1_-] ?)\Q$num/i or $f =~ m/episode([0-1_-] ?)\Q$num/i) {
            $flast = "$movie.S$season"."E$num.$cont";
            rename($f, $flast) or die "\nError while renaming $f !";
            $num++;
        }
    }

    if (-d "$npath") {
        $exist = 1;
        print "\n$npath";
        }
    else {
        mkdir($npath) or die "\nError while making new directory";
        $exist = 1;
    }

    sleep(1);

    if ($exist == 1) {
        foreach my $f (@files) {
            $npath = "Saison "."$season/$f";
            mv($f, $npath) or die "\nError while moving $f";
            print "\n$f done !";
            $ind++;
        }
        print "\n\n$ind files processed successfully !";
    }
}

Upvotes: 0

Views: 32

Answers (1)

Borodin
Borodin

Reputation: 126722

The problem is that you are renaming the files and then moving them, but after the rename the file no longer exists under its old name in the @files array

You can use mv to change the name of the file as well as putting it into a new directory. In other words, you can call

mv 'movie.title.s01.e08.(2008).[1080p].mkv', 'Saison 01/Movie TitleS01E08.mkv'

which simplifies your program considerably. You just need to create the new directory if it doesn't exist, and then call mv $f, "$npath/$flast" for each name in @files

Upvotes: 1

Related Questions