Windows – Creating a folder from first 5 characters of filename in a batch file

batch filecommand linewindows

Here's what I have:


I would like to have the script read the first 5 digits from the file, create a folder with those digits, and include the letter T before it.

The result after running should be like this:


Currently, I have this, which does the function; I just can't figure out where to put the SET command to extract the 5 characters.

@echo off
for %%a in (*.*) do (
md "T%%a" 2>nul
move "%%a" "T%%~a"  

I think this needs to be added to choose only the first 5 characters:

set first5=%%a:~5,1%


Best Answer

  • @echo off
    for /f %%a in ('dir /a-d /b') do (
      if not "%%~dpnxa"=="%~dpnx0" call :func "%%~a"
    goto :EOF
    set file=%~1
    set dir=%file:~0,5%
    md "T%dir%" 2>nul
    move "%file%" "T%dir%" 
    goto :EOF

    This will process files (= no dirs) in the working directory. I also added a check to prevent the script from moving the batch file itself in case it happens to be located in the wd.