1

I have a file directory called "Parts". Within that folder I have files that I need to run a batch file on to move to their correct folders. Example

12345 test.pdf
12345 test.jpg
12346 test.pdf
12345 Folder
12346 Folder

If the filename starts with the folder number, move it into that folder. The folder will always be setup prior.

harrymc
  • 480,290

2 Answers2

1

Explanation of the code

  • Use one for to iterate folder content %%A with a pattern containing at least one space.
  • Another for /fis needed to split the name %%A into two parts, one before the first space tokens=1 = %%B and the rest tokens * = %%C.
  • Move the original file %%A to the subfolder %%B with the name %%C
@Echo off
Pushd "Folder path"
for %%A in ("* *.*") do for /f "tokens=1*" %%B in ("%%A") do (
  Move "%%A" "%%B\%%C"
)
popd
Wasif
  • 8,474
1

enter image description here


The answer considers this comment: This only works if there is a space after the number. I need something that will always count the first 5 digits and go off of that. - @Brandon Hurst


So, my limited English not help to explain this code and the mechanic apply here to do this job...

Well, basically, this take files out in dir command and get the five 1st characters to echo in unicode format/layout by cmd/u and using the findstr filter for to get only numbers, after, check if folder match/exist, in case positive, this code will copy this files to a same folder where five 1st string...

@echo off && setlocal EnableDelayedExpansion & title <nul & call title ..\%~nx0

cd/d "%~dp0" && for /f tokens^=*eol^=* %%i in ('dir /b/a:-d .\*.* ^|find/v "%0"
')do set "_f=%%~ni" && set "_fc=%%~fi" && set "_N=" && set "_at5=!_f:~,5!" && (
for /f %%N in ('cmd /u/c "echo=!_at5!^<nul|findstr [0-9]"')do set "_N=!_N!%%~N"
if exist "!_N!\." echo=!_fc! ^> .\!_N!\%%~nxi &cmd/v/cmove "!_fc!" "!_N!\">nul)

rem./ you can put/do some more tasks here in your bat... && endlocal && exit /b

  • Output:

G:\SUPER_USER\Q1507690\54321testX.pdf > .\54321\54321testX.pdf
G:\SUPER_USER\Q1507690\54321-test.jpg > .\54321\54321-test.jpg
G:\SUPER_USER\Q1507690\12345 test.jpg > .\12345\12345 test.jpg
G:\SUPER_USER\Q1507690\12345,test.pdf > .\12345\12345,test.pdf
G:\SUPER_USER\Q1507690\12346 test.jpg > .\12346\12346 test.jpg
G:\SUPER_USER\Q1507690\12346.test.pdf > .\12346\12346.test.pdf
G:\SUPER_USER\Q1507690\12346_test.jpg > .\12346\12346_test.jpg

Obs.: I´ll try update when some friends help me with English, so, really sorry my limited English...

Io-oI
  • 8,193