Search code examples
batch-filexcopy

How to move files from subfolders with certain extension to different subfolder


I have tens of thousands .jpg's in folders like .\[date]\jpg , for example:

.\2018_03_01\jpg
.\2018_03_02\jpg

...and so on.

I need to move them one step backwards, i.e.

.\2018_03_01\jpg\*.jpg

...to

.\2018_03_01\*.jpg

...and so on.

All of those date-named folders don't contain the jpg subfolder these occasions should be dealt with.

I suppose this can be done with XCopy or traditional .bat batch, but how?


Solution

  • The command XCOPY is for copying files and entire directories and not for moving files.

    The solution is using a FOR loop in a command prompt window. There is no need for a batch file.

    Open a command prompt window in the directory containing the subdirectories 2018_03_01 and 2018_03_02 and run following command line:

    @for /D %I in (*) do @if exist "%I\jpg\*.jpg" echo Move files from %I\jpg ... & move "%I\jpg\*.jpg" "%I\" & rd "%I\jpg"
    

    This FOR command line processes each non hidden subdirectory in current directory.

    For each subdirectory an IF condition is executed to check existence of any *.jpg file in subdirectory jpg of current date subdirectory.

    On true condition first an information is output with ECHO telling you what happens next. Then the command MOVE is executed to move the JPEG files from subdirectory jpg one level up in directory hierarchy and last command RD is executed to delete subdirectory jpg if it is empty now.

    For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

    • echo /?
    • for /?
    • if /?
    • move /?
    • rd /?

    See also Single line with multiple commands for an explanation of & used twice in the command line.