Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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%


share|improve this question
@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.

share|improve this answer

You can use this to get the first five characters:

set first5=%a:~0,5%

set assigns the value after the = to first5. %a% would return the value of variable a, by adding the following characters you reference the range starting at character 0 and the next five ones.

share|improve this answer
Thank you for the answer, I am just not sure how to compile it together to make it work. for %%a in (.) do ( set first5=%a:~0,5% md "T%%a" 2>nul move "%%a" "T%%a" ) Doesn't seem to solve it. – billieh Oct 25 '11 at 19:04
If you want to access some variable, use %varname%, not %%varname. Try echo %first5. You never used first5 after SETting it? – Jens Erat Oct 25 '11 at 19:10
Could you provide some explanation about what your code does? – Tom Wijsman Oct 31 '11 at 21:42
Did so. As these are primarily very basic operations I recommend you to have a look at some batch-tutorials (can't reference any, sorry - have a look yourself, most look a lot like beepworld and 90's but are still fine). More information about set can be got by calling set help set /?. – Jens Erat Nov 1 '11 at 0:10

As long as you're going through the trouble to learn something, why not learn something worthwhile? In PowerShell:

$x = gci ; $x | % { $d = 'T' + $_.Name.Substring(0,5) ; mkdir $d ; move $_ $d } | Out-Null
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.