Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bulk Rename Files in a Folder - PHP

Tags:

php

I have 1000 images in a Folder, which has SKU# word in all the images. For examples

WV1716BNSKU#.zoom.1.jpg
WV1716BLSKU#.zoom.3.jpg

what i need to do is read all the filenames and rename it to the following

WV1716BN.zoom.1.jpg
WV1716BL.zoom.3.jpg

So remove SKU# from filename, is it possible in PHP to do bulk renaming ?

like image 696
user580950 Avatar asked Feb 14 '11 14:02

user580950


6 Answers

Yeah, just open the directory and create a loop to access all images and rename them, like:

<?php

if ($handle = opendir('/path/to/files')) {
    while (false !== ($fileName = readdir($handle))) {
        $newName = str_replace("SKU#","",$fileName);
        rename($fileName, $newName);
    }
    closedir($handle);
}
?>

References:

http://php.net/manual/en/function.rename.php

http://php.net/manual/en/function.readdir.php

http://php.net/manual/en/function.str-replace.php

like image 86
Aston Avatar answered Sep 29 '22 02:09

Aston


piece of cake:

foreach (array_filter(glob("$dir/WV1716B*.jpg") ,"is_file") as $f)
  rename ($f, str_replace("SKU#", "", $f));

(or $dir/*.jpg if number doesn't matter)

like image 29
Kamil Tomšík Avatar answered Sep 29 '22 01:09

Kamil Tomšík


The steps to completing this is pretty simple:

  • iterate over each file using fopen, readdir
  • for each file parse the file name into segments
  • copy the old file into a new directly called old (sanity reasons)
  • rename the root file top the new name.

A small example:

if ($handle = opendir('/path/to/images'))
{
    /* Create a new directory for sanity reasons*/
    if(is_directory('/path/to/images/backup'))
    {
         mkdir('/path/to/images/backup');
    }

    /*Iterate the files*/
    while (false !== ($file = readdir($handle)))
    {
          if ($file != "." && $file != "..")
          {
               if(!strstr($file,"#SKU"))
               {
                   continue; //Skip as it does not contain #SKU
               }

               copy("/path/to/images/" . $file,"/path/to/images/backup/" . $file);

               /*Remove the #SKU*/
               $newf = str_replace("#SKU","",$file);

               /*Rename the old file accordingly*/
               rename("/path/to/images/" . $file,"/path/to/images/" . $newf);
          }
    }

    /*Close the handle*/
    closedir($handle);
}
like image 45
RobertPitt Avatar answered Sep 29 '22 01:09

RobertPitt


Well, using iterators:

class SKUFilterIterator extends FilterIterator {
    public function accept() {
        if (!parent::current()->isFile()) return false;
        $name = parent::current()->getFilename();
        return strpos($name, 'SKU#') !== false;
    }
}
$it = new SkuFilterIterator(
    new DirectoryIterator('path/to/files')
);

foreach ($it as $file) {
    $newName = str_replace('SKU#', '', $file->getPathname());
    rename($file->getPathname(), $newName);
}

The FilterIterator basically filters out all non-files, and files without the SKU# in them. Then all you do is iterate, declare a new name, and rename the file...

Or in 5.3+ using the new GlobIterator:

$it = new GlobIterator('path/to/files/*SKU#*');
foreach ($it as $file) {
    if (!$file->isFile()) continue; //Only rename files
    $newName = str_replace('SKU#', '', $file->getPathname());
    rename($file->getPathname(), $newName);
}
like image 22
ircmaxell Avatar answered Sep 29 '22 01:09

ircmaxell


You can also use this sample:

$directory = 'img';
$gallery = scandir($directory);
$gallery = preg_grep ('/\.jpg$/i', $gallery);
// print_r($gallery);

foreach ($gallery as $k2 => $v2) {
    if (exif_imagetype($directory."/".$v2) == IMAGETYPE_JPEG) {
        rename($directory.'/'.$v2, $directory.'/'.str_replace("#SKU","",$v2));
    }
}
like image 41
a.4j4vv1 Avatar answered Sep 29 '22 03:09

a.4j4vv1


$curDir = "/path/to/unprocessed/files";
$newdir = "/path/to/processed/files";

if ($handle = opendir($curDir)) 
{
    //make the new directory if it does not exist
    if(!is_dir($newdir))
    {
         mkdir($newdir);
    }

    //Iterate the files
    while ($file = readdir($handle))
    {
            // invalid files check (directories or files with no extentions)
            if($file != "." && $file != "..")
            {
                //copy
                copy($curDir."/".$file, $newdir."/".$file);
        
                $newName = str_replace("SKU#","",$file); 
                
                //rename
                rename($newdir."/".$file, $newdir."/".$newName.".jpg");
            
            }
    }
    closedir($handle);
}
like image 22
Liza Avatar answered Sep 29 '22 03:09

Liza