Batch Script to Create New Folders from First and Second Part of Folder Name

Abstract: Automates creating subdirectories from the first two segments of parent folder names using batch script tokenization.

Created: 2026-08-27 by

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 the for /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 the delims 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. Use echo 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 the tokens=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, the for /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 the mkdir 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 add move 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.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More