'Automatically create folders based on unique key
I have various files with the same structure, they begin with a unique key and a hyphen followed by the name of the file. Examples below:
- 100023525_Document_1
- 100023525_Document_2
- 102008006_Document_1
- 102008006_Document_2
- 102008006_Document_3
I want to be able to generate folders for each unique key and have the files moved into them automatically. I have found the following code below written in batch that does so but puts each file into its own separate folder.
@echo off
for %%i in (*) do (
if not "%%~ni" == "organize" (
md "%%~ni" && move "%%~i" "%%~ni"
)
)
This puts the following files:
to
I want the code to be able to put the initial files into folders like this, based on the unique key:
How could I modify the initial batch code to do this? Thanks!
Solution 1:[1]
Note: I decided to simplify the code here.
There are probably easier and faster ways to do this, but here is one option if your files are all in the same format. You will want to do this from the folder containing your files:
for /f "delims=_" %%b in ('dir /b *.pdf') do (
if not exist %%b\. @mkdir "%%b"
)
for /f "tokens=1,2,3 delims=_" %%b in ('dir /b *.pdf') do (
if not exist "%%b\%%b_%%c_%%d" @echo move "%%b_%%c_%%d" "%%b\%%b_%%c_%%d"
)
For more information on how this works, please read the documentation on for /f. Take note of how the tokens and delimiters work.
This will show you the items it will move and where. Remove @echo
in front of move to do the actual move.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |