none
Batch - Move files to new folder, by matching string within filename RRS feed

  • Question

  • Hello... Assume the following test conditions:
    In folder C:\images I have several image files named:

    100.00001.png
    100.00002.png

    100.00003.png
    200.00001.png
    200.00002.png
    200.00003.png

    The batch should find all files with matching "100" string prefix (before first "." delimiter), and move it to a folder within C:\images which is named after the search string (i.e. C:\images\100\). What I have so far finds the correct files (I think), but I'm having trouble moving them, I believe a nested for is required but my efforts so far have been failure. What I must do to get this working? 

    @echo off

    for /f "delims==" %%i in ('dir /b C:\images ^| findstr "100"') do (
    echo %%i
    rem MD C:\images\%%i
    MOVE C:\images\%%i "C:\capture\100\"
    )
    pause

    • Edited by F_Gordon Wednesday, March 25, 2015 10:23 PM
    Wednesday, March 25, 2015 7:59 PM

Answers

  • Your description is a little unclear. It uses the folder name "C:\Images" but the code uses "C:\Capture". I also wonder if your real aim is this: With file names of this type:

    100.00001.png
    100.00002.png

    100.00003.png
    200.00001.png
    200.00002.png
    200.00003.png

    grab the prefix (=the string left to the first dot)
    create a folder C:\Images\{prefix}
    move the file to this folder.

    If so then this batch file would do it:

    @echo off
    SetLocal EnableDelayedExpansion

    for %%a in (C:\images\*.png) do (
        for /F "tokens=3 delims=.\" %%b in ('echo %%a') do set Prefix=%%b
        echo if not exist C:\Images\!Prefix! md C:\Images\!Prefix!
        echo move %%a C:\Images\!Prefix!
    )

    You must run the code from a Command Prompt so that you can see what it does. To activate it, you need to remove the two "echo" commands towards the bottom.
    What should happen if a file of the same name already exists in the target folder?
    Note also that indenting your code makes it a lot more readable!

    • Marked as answer by F_Gordon Wednesday, March 25, 2015 9:55 PM
    Wednesday, March 25, 2015 8:53 PM