Windows batch file to move files to subfolders based on first word in file name?
I am bit of a batch file noob, so I'd really appreciate your help. I have a ton of files stored in a single directory which I wish to sort into subfolders based on the first word in their filenames. So, I have files like these:
C:\Folder\Wedding2018 img20929.jpg
C:\Folder\Wedding2018 entrance.mov
C:\Folder\Wedding2018 registry of guests.pdf
C:\Folder\HorseRiding2017 spirit1.jpg
C:\Folder\HorseRiding2017 guests.txt
C:\Folder\HorseRiding2017 certificate.pdf
C:\Folder\HorseRiding2017 jumping.mov
And I wish to move all files to subfolders based on the first word, ending up like this:
C:\Folder\Wedding2018\img20929.jpg
C:\Folder\Wedding2018\entrance.mov
C:\Folder\Wedding2018\registry of guests.pdf
C:\Folder\HorseRiding2017\spirit1.jpg
C:\Folder\HorseRiding2017\guests.txt
C:\Folder\HorseRiding2017\certificate.pdf
C:\Folder\HorseRiding2017\jumping.mov
I've found a couple of scripts that almost do what I need, but I don't have the chops to bring it home:
"Need a script to create folders based on file names, and auto move files"
"How to extract second word of the string via windows batch"
I just can't work out how to integrate the script to grab the first word and make a directory to which the files will be moved.
Can you help me get this across the line?
- Use one for to iterate folder content
%%A
with a pattern containing at least one space. - Another
for /f
is needed to split the name%%A
into two parts, one before the first spacetokens=1
=%%B
and the resttokens *
=%%C
. - If a folder with the name of
%%B
doesn't exist create it - Move the original file
%%A
to the subfolder%%B
with the name%%C
:: Q:\2018\06\11\SU_1330475.cmd
@Echo off
PushD C:\folder
for %%A in ("* *.*") do for /f "tokens=1*" %%B in ("%%A") do (
If not exist "%%B" MD "%%B"
Move "%%A" "%%B\%%C"
)
PopD
> tree /f
C:.
│ SU_1330475.cmd
│
└───folder
├───HorseRiding2017
│ certificate.pdf
│ guests.txt
│ jumping.mov
│ spirit1.jpg
│
└───Wedding2018
entrance.mov
img20929.jpg
registry of guests.pdf