Search code examples
phpbatch-filerenamefile-renamebatch-rename

How to rename a lot files with a loop?


I want to rename 420 files with a loop, but I don't know how.

In my project I created 420 images with fopen();

fopen($meal->imagepath, "w");

Since fopen searches for a existing file and I didn't had these, the function created my 420 files via a loop and they have the correct names. The problem now is, that these images have no properties like height, width or background-color.

Therefore I would like to create one file manually in paint and copy this file 420 times and then rename them by refering on a txt file with my 420 correct names. I think this should be possible, but how?

Thanks you


Solution

  • Since this sounds like a one-shot thing I leave out the error handling

    php directly copying the files

    foreach( file('names.txt', FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES) as $target)
        copy('source.png', $target);
    }
    

    see also: http://docs.php.net/copy , http://docs.php.net/function.file

    php creating a batch file:

    file_put_contents('rename.sh', '#!/bin/bash');
    foreach( file('names.txt', FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES) as $target)
        file_put_contents('rename.sh', "cp source.png $target\r\n", FILE_APPEND);
    }
    

    see also: http://docs.php.net/file_put_contents

    shell/xargs only:

    <source.txt xargs -L 1 cp source.png
    

    see also: https://en.wikipedia.org/wiki/Xargs

    Powershell:

    gc .\source.txt | %{ copy source.png $_ }
    

    see also: Using the Get-Content Cmdlet