This batch script extracts the first two segments of a folder name, separated by a delimiter like an underscore or hyphen, and creates corresponding subdirectories. By leveraging the for /f loop with tokenization, you can parse directory names dynamically to automate file organization without manual intervention.
Understanding the Parsing Logic
The core challenge in this task is splitting a single string into distinct parts. In Windows Command Prompt (CMD), strings are not arrays but simple text sequences. To isolate specific parts of a filename, we use thefor /f command, which iterates over lines of text and splits them based on delimiters.
A folder name such as Project_Alpha_Data needs to be split into Project and Alpha. The for /f command uses the tokens option to specify which parts of the line to assign to variables. For example, tokens=1,2 tells CMD to take the first word and the second word, ignoring everything after the second delimiter for those specific variables.
You must define the delimiter using the delims option. Common delimiters include underscores (_), hyphens (-), or spaces. If your folder names use different separators, adjust the delims parameter accordingly. This approach ensures that the script remains flexible across different naming conventions within the same directory structure.
The Batch Script Implementation
Below is a robust script that processes all immediate subdirectories in the current location. It extracts the first two tokens and creates new folders named after those tokens inside each original folder.@echo off
setlocal enabledelayedexpansion
:: Change to the target directory if needed
cd /d "C:\Path\To\Your\Folders"
:: Loop through each immediate subdirectory
for /d %%D in (*) do (
:: Get the folder name
set "folderName=%%~nxD"
:: Extract the first and second parts using a delimiter (e.g., underscore)
for /f "tokens=1,2 delims=_-" %%A in ("!folderName!") do (
set "part1=%%A"
set "part2=%%B"
:: Check if both parts exist before creating folders
if defined part1 if defined part2 (
echo Processing: !folderName! -> !part1!, !part2!
:: Create the new directories inside the original folder
mkdir "!folderName!\!part1!" 2>nul
mkdir "!folderName!\!part2!" 2>nul
echo Created folders for !part1! and !part2!
) else (
echo Skipping !folderName! due to missing parts
)
)
)
endlocal
echo Done.
pause
This script begins by enabling delayed variable expansion with setlocal enabledelayedexpansion. This is critical because standard CMD variables do not update correctly within loops when modified dynamically. Using exclamation marks (!) instead of percent signs (%) allows the script to read the most recent value of the variable during execution.
The outer for /d loop iterates through every directory in the current path. The %%~nxD syntax extracts just the name and extension of the directory, ensuring we work with clean strings. Inside this loop, the inner for /f command parses the folderName variable. The tokens=1,2 flag assigns the first segment to %%A and the second to %%B. The delims=_- setting means either an underscore or a hyphen will act as a separator.
After parsing, the script checks if part1 and part2 are defined. This prevents errors if a folder name has only one segment or contains special characters that break the parsing logic. Finally, the mkdir command creates the new subdirectories. The 2>nul redirect suppresses error messages if the folder already exists, keeping the console output clean.
Customizing Delimiters and Paths
If your folder names use a different separator, such as a space or a period, modify thedelims argument in the inner for /f loop. For instance, change delims=_- to delims= . to handle spaces and dots. Note that spaces are tricky in CMD; if your names contain spaces, ensure the string is properly quoted, as shown in the script with "!folderName!".
You can also target a specific directory rather than the current working directory. Replace the cd /d line with the full path to your target root folder. Alternatively, pass the path as an argument to the script using %1, allowing you to drag and drop folders onto the batch file for processing.
For more advanced scenarios where you need to create folders above the current level, consider reviewing how to manage parent directory structures in batch files. This can help if your parsing logic requires moving files up the tree rather than down. Additionally, if you need to move the original contents into these newly created folders, you might want to explore techniques for renaming and moving files to parent directories to complete the automation workflow.
Error Handling Best Practices
Always test the script on a small subset of data first. Useecho commands before mkdir to verify that the parsed variables contain exactly what you expect. If the parsing fails, check for trailing spaces or invisible characters in the folder names. You can strip whitespace by using the ~ modifier in variable expansion, such as %%~A, which removes surrounding quotes and spaces.
Frequently Asked Questions
What if my folder name has more than two parts?
The script ignores any parts beyond the second token because of thetokens=1,2 setting. If you need to capture all remaining parts, use tokens=1,* to assign everything after the first delimiter to the second variable. This ensures that partial names like "Project Alpha Data" result in "Project" and "Alpha Data".
How do I handle folder names with special characters?
Special characters like parentheses or exclamation marks can break CMD parsing. Always wrap variables in quotes and enable delayed expansion. If issues persist, rename the folders to remove problematic characters before running the script, or use PowerShell for more robust string manipulation capabilities.Can I run this script recursively on nested folders?
No, thefor /d loop only processes immediate subdirectories. To process nested folders, replace it with for /r, which traverses the entire directory tree. Be cautious as this may create duplicate folder structures at multiple levels if not carefully managed.
Why does my script fail with 'is not recognized as an internal or external command'?
This error usually occurs if themkdir command is misspelled or if the path contains unescaped spaces. Ensure you are using mkdir or md and that all paths containing spaces are enclosed in double quotes. Also, verify that you are running the script in a valid Windows environment.
Is there a way to copy files into the new folders automatically?
Yes, you can addmove commands after creating the directories. For example, move "!folderName!\*.*" "!folderName!\!part1!\" would move all files from the root of the original folder into the newly created part1 folder. Always backup your data before automating file movements.