Home > database >  Creating folders and subfolders in batch
Creating folders and subfolders in batch

Time:12-07

I'm trying to write a batch file to sort a bunch of peoples documents into alphabetized folders. I started with the code below to create the folders and the idea was to create a folder for each letter of the alphabet then fill it with folders for each person with a last name that starts with that letter. the naming scheme is supposed to be "Lastname, Firstname -#A123" (123 just being an id number associated with the name)

The outside loop works fine but the inside loop doesn't do anything at all so I'd appreciate any advice anyone has. Thank you very much.

FOR %%X IN (A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z) DO (
    MD C:\Users\evanm\Documents\%%X
    FOR /F "tokens=1,2,3" %%A IN (NameList.txt) DO (
        SET "newFileName=%%A, %%B - #A%%C"
        SET “n=%%A”
        SET “sortLetter=%n:~0,1%”
        IF /I str EQU %%X (
            MD C:\Users\evanm\Documents\%%X\newFileName
        )
    )
)

CodePudding user response:

firstly, you need delayedexpansion.

I am also not sure what you're trying to match here IF /I str EQU %%X ( what is str? You never created the variable, even if you did, you forgot to make it a variable %str% or with delayedexpansion it will be !str!.

Then there are these inverted commas, , don't do that, use double quotes ". The last MD command , you are not using the variables you created. newFileName is a bare word, the variable should be %newFileName% or with delayedexpansion, which you need here, !newFileName!.

Finally, You are creating a variable SET "newFileName=%%A, %%B - #A%%C" with an additional comma, remove it.

a fixed version of your own code:

@echo off
setlocal enabledelayedexpansion
FOR %%X IN (A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z) DO (
    MD C:\Users\evanm\Documents\%%X
    FOR /F "tokens=1,2,3" %%A IN (NameList.txt) DO (
        SET "newFileName=%%A %%B - #A%%C"
        SET "n=%%A"
        SET "sortLetter=!n:~0,1!"
        IF /I !sortletter! EQU %%X (
            MD "C:\Users\evanm\Documents\%%X\!newFileName!"
        )
    )
)

That being said, I would personally have done this:

@echo off
setlocal enabledelayedexpansion
for /F "usebackq tokens=*" %%A IN ("NameList.txt") DO (
        set "line=%%~A"
        set "letter=!line:~0,1!"
        md "%userprofile%\Documents\!letter!\!line!">nul
)

I do not need to loop through the alphabet to get the letters seeing as the names already has these letters. So even if a user with a surname starting with X is not in your list, it will eventually create the folder once such a person gets added to the list.

  • Related