Run this batch file from the parent folder of Reports folder:
for /f "delims=" %%a in ('dir /b /s "Reports folder\*.rep"') do for /f "tokens=2 delims=-" %%i in ("%%~a") do (
if not exist "%%~dpa%%i\" md "%%~dpa%%i"
move "%%~a" "%%~dpa%%i\"
)
%%a and %%i are the variables used in the two for loops.The former contains the full paths to the .REP files (courtesy the outer loop), and the latter contains the folder names extracted from the file names (courtesy the inner loop).
for /? is what anyone interested should really be looking at for more help (note that in batch files the % signs are doubled):
%~I - expands %I removing any surrounding quotes (")
%~dI - expands %I to a drive letter only
%~pI - expands %I to a path only
So what does "%%~dpa%%i" mean? Suppose one of the .REP files located by the dir command is "C:\Reports folder\123-Chemistry-101.rep".
%%~dpa would mean the drive letter and path of the file minus the surrounding quotes, i.e. C:\Reports folder\.
%%i would, as I noted above, be the folder name extracted from the file name (anything between two hyphen delimiters), so in this case Chemistry.
Putting it all together, "%%~dpa%%i" would for this file expand to "C:\Reports folder\Chemistry", because that's where we want the file to be moved to.
Batchwill never die...Here's an edit for recursive as you asked. The trick is to get the full path for files in subdirectories. Then, what about target dir ? Should it have sub-folders ? Assuming "no" here. My script got "too much" lines in order to be make it very clear...However it could be shortened... – user2196728 May 28 '15 at 19:43D:\New folder. I have D:\New folder\123-Chemistry-101.rep, D:\New folder\123-Phys Ed-101.rep, D:\New folder\New folder\123-Chemistry-101.rep and D:\New folder\New folder\123-Phys Ed-101.rep (just 4 files in two levels of folders). – Karan May 28 '15 at 19:53D:\New folderare moved into respective sub-folders, but the files underD:\New folder\New folderaren't touched. – Karan May 28 '15 at 20:34D:\New folder\ChemistryandD:\New folder\New folder\Chemistry, i.e. at whichever level it finds .REP files, at that level it should create appropriate sub-folders and move the files to them. – Karan May 28 '15 at 20:42New folderwith 2 REP files,New folder\New folderwith another 2 (same names) andNew folder\New folder\New folderwith another 2 (again same names) it fails again. Forget it, don't want to bother you and waste more of your time on it. I'll work on it later. Thanks a lot! – Karan May 29 '15 at 00:48