1

I have a set of files in a folder with names like test! - 01.avi. I want to make a new folder for each file with the same name and then move the file into that folder. I have everything but how to pull in the "!" and copy the file to the folder.

@ECHO OFF
setlocal enabledelayedexpansion
set "sourcedir=Z:\test"
set folder=null
set file=null
PUSHD %sourcedir%
FOR /f "tokens=* delims=?" %%a in ( 'dir /b /a-d "*[720p].*"'
 ) DO (
  SET file=%%a
  FOR /f "tokens=1,2,* delims=]-" %%b in ("%%a" "[*] * - * [720p].*"
   ) DO (
   FOR /f "tokens=* delims= " %%e in ("%%c"
    ) DO (
     SET folder=%%e
     FOR /l %%f in (1,1,31) do if "!folder:~-1!"==" " set folder=!folder:~0,-1!
     MD "!folder!"
     MOVE "!file!" .\"!folder!"\ 
     )  
    )   
 )
POPD
GOTO :EOF

Thanks for taking a look

Joel Coel
  • 12,932
  • 14
  • 62
  • 100
Pyrotek
  • 13
  • 2

1 Answers1

0

Better to cope with file names keeping delayed expansion disabled. Treat variables assigned within a (code block) in a subroutine as follows:

@ECHO OFF
SETLOCAL EnableExtensions DisableDelayedExpansion

set "sourcedir=D:\bat\Unusual Names"
PUSHD %sourcedir%

dir /b /a-d "*!a*.*"

FOR /f "tokens=* delims=?" %%a in ( 'dir /b /a-d "*!a*.*"') DO (

  SET "file=%%~nxa"

  rem observe instructions "make a new folder for each file with the same name"
  rem suppose that without extension
  SET "folder=%%~dpna"

  call :DoDelayedExpansion
)
POPD

ENDLOCAL
goto :eof

:DoDelayedExpansion
  echo(
  echo MD "%folder%\" 2>NUL
  echo MOVE "%file%" "%folder%\" 
goto :eof

Next script gives an example only using my existing test data set. Note:

  • use set "variable=value" syntax with double quotes to escape some characters of a special meaning in batch scripting, e.g. |, &, <, > etc., and to ensure there are no (accidentally forgotten) trailing white spaces;
  • both MD and MOVE commands are merely echoed for debugging purposes; remove all echo no sooner than debugged.

Output:

==>D:\bat\SF\694616.bat
01exclam!ation.txt
02exc!lam!ation.txt

MD "D:\bat\Unusual Names\01exclam!ation\"
MOVE "01exclam!ation.txt" "D:\bat\Unusual Names\01exclam!ation\"

MD "D:\bat\Unusual Names\02exc!lam!ation\"
MOVE "02exc!lam!ation.txt" "D:\bat\Unusual Names\02exc!lam!ation\"

==>

Resources (required reading):

JosefZ
  • 1,564
  • 1
  • 10
  • 18