Search code examples
batch-filecommandwhitespacedelimiter

How do I include a space in the delimiter of a FOR /F (batch file)


The following command creates folders based on the part of a filename before a delimiter (in this case, a dash, or -):

setlocal EnableExtensions DisableDelayedExpansion
set "SourceDir=C:\Users\T\Source"
set "DestDir=C:\Users\T\Dest"

for /F "eol=| delims=" %%A in ('dir /B /A-D-H "%SourceDir%\*-*.jpg" 2^>nul') do (
    for /F "eol=| tokens=1 delims=-" %%B in ("%%~nA") do (
        md "%DestDir%\%%B" 2>nul
        REM move /Y "%SourceDir%\%%A" "%DestDir%\%%B\"
    )
)

endlocal

Specifically, the delimiter command is here:

delims=-

But I need to include a space in the delimiter, both before and after the dash. How would I include a space in delims?


Solution

  • If you assign the file name to an environmental variable you can then use string substitution to manipulate that variable. In the first substitution you can remove the first part of the file name by using a wildcard with the string delimiter. This will give you the ending portion of the file name. Now that you have the ending portion of the file name you can turn around and use the string delimiter and the ending portion of the file name to be removed from the original file name.

    setlocal EnableExtensions DisableDelayedExpansion
    set "SourceDir=C:\Users\T\Source"
    set "DestDir=C:\Users\T\Dest"
    
    for /F "eol=| delims=" %%A in ('dir /B /A-D-H "%SourceDir%\*-*.jpg" 2^>nul') do (
        set "string=%%~A"
        setlocal enabledelayedexpansion
        SET "end=!string:* - =!"
        FOR /F "delims=" %%G IN ("!end!") do set "begin=!string: - %%~G=!"
        md "%DestDir%\!begin!" 2>nul
        REM move /Y "%SourceDir%\%%A" "%DestDir%\!begin!\"
        endlocal
    )
    
    endlocal