Search code examples
windowsbatch-filebatch-rename

Batch rename and move files to folders based on filename has error due to single hyphen


I have several files that I want renamed and moved to their respective folders based on their filename. My files are in the format:

village--rural--rodriguez.txt
city--rural--santa-ana.txt
city--urban--san-diego.txt
city--no-data--san-marino.txt

and I want the final output to be:

village (folder) containing rural (subfolder) containing rodriguez.txt

city (folder) containing rural (subfolder) containing santa-ana.txt

city (folder) containing urban (subfolder) containing san-diego.txt

city (folder) containing no-data (subfolder) containing san-marino.txt

I have read other similar questions and tried this code which works for most files. The only problem is that my some of my filenames have single hyphens - in them (like no-data in city--no-data--san-marino.txt), which makes the batch file ignore the processing of such files:

@ECHO OFF
SETLOCAL
SET "sourcedir=c:\Users\Documents"
PUSHD %sourcedir%
FOR /f "tokens=1,2*delims=-" %%a IN (
 'dir /b /a-d *--*--*.*'
 ) DO if "%%c" neq "" if exist "%%a--%%b--%%c" (  
 MD "%%a" 2>nul
 MD "%%a\%%b" 2>nul
 ren  "%%a--%%b--%%c" "%%c"
 MOVE "%%c" ".\%%a\%%b\" >nul
)
POPD
GOTO :EOF

How can I make the batch file process the filenames, whether with hyphens or not?


Solution

  • You could use this option if you think it works better for you:

    @Echo Off
    SetLocal EnableDelayedExpansion
    Set "SourceDir=%UserProfile%\Documents"
    CD /D "%SourceDir%" 2>Nul || Exit /B
    Set "i=0"
    For %%A In (*--*--*.*) Do Call :Sub "%%A"
    Exit /B
    
    :Sub
    Set "_=%~1"
    Set "i=1"
    Set "_!i!=%_:--="&Set /A i+=1&Set "_!i!=%"
    If Not Exist "%_1%\%_2%\" MD "%_1%\%_2%"
    Move /Y %1 "%_1%\%_2%\%_3%">Nul