Batch Script to Take First & Second Part of Folder Name and Create New Folders From Them

Abstract: Extracts the first two parts of folder names separated by a delimiter and creates new directories from them.

Created: 2026-08-03 by

To extract the first and second parts of a folder name using a batch script, you can utilize string manipulation operators to split the directory path. By iterating through folders in a target directory, parsing the base name against a delimiter like a hyphen or underscore, you can dynamically generate new subdirectories based on these extracted segments.

Understanding String Manipulation in Batch

Batch scripting in Windows relies heavily on environment variables and specific syntax for manipulating text. The core challenge here is isolating specific components of a filename that contains multiple parts separated by a common character. In batch files, this is achieved using the ~ operator combined with start and end indices within variable expansion. For example, if you have a variable %var% containing "Part1-Part2-Part3", you can extract substrings. However, batch does not have a native split() function like Python or JavaScript. Instead, you must rely on known delimiters or fixed positions. The most robust approach for this task involves using the for /f loop with the delims option, which allows you to parse strings based on a specified separator. This method is efficient because it handles the parsing logic internally without requiring external tools or complex arithmetic. When dealing with folder names, it is crucial to distinguish between the full path and just the base name. The %~n1 syntax is often used to retrieve the name of a file or folder without its extension or path. Combining this with delimiter-based parsing ensures that you are working with clean data before creating new directories.

Step-by-Step Script Implementation

To create a functional script, follow these steps to build a solution that processes all folders in a specific location.
  1. Define the Target Directory: Set a variable pointing to the root folder where your source directories reside. This makes the script portable and easy to modify.
  2. Iterate Through Folders: Use a for /d loop to cycle through each subdirectory in the target path. This ensures only directories are processed, ignoring files.
  3. Extract the Base Name: Inside the loop, capture the name of the current folder. You can use %%~nF if F is the loop variable representing the full path.
  4. Parse the Name: Use for /f with delims=- (or your chosen delimiter) to split the base name into tokens. Assign the first token to one variable and the second to another.
  5. Create New Directories: Use the mkdir command to generate new folders. You can structure them as FirstPart_SecondPart or place them in separate locations depending on your needs.
Here is a concrete example of the code structure:
@echo off
setlocal enabledelayedexpansion

:: Define the source directory
set "SourceDir=C:\Data\RootFolder"

:: Change to the source directory
cd /d "%SourceDir%"

:: Loop through each folder
for /d %%F in (*) do (
    :: Get the folder name without path
    set "FolderName=%%~nF"
    
    :: Split by hyphen '-'
    for /f "delims=- tokens=1,2" %%A in ("!FolderName!") do (
        set "Part1=%%A"
        set "Part2=%%B"
        
        :: Create new folder combining both parts
        mkdir "!Part1!_!Part2!" 2>nul
        echo Created folder: !Part1!_!Part2! from !FolderName!
    )
)

endlocal
pause
This script assumes a delimiter of a hyphen. If your folder names use underscores, change delims=- to delims=_. The 2>nul redirection suppresses errors if the directory already exists, making the script idempotent.

Handling Edge Cases

Not all folder names will have exactly two parts. Some might have three, while others might have none. The tokens=1,2 specification ensures that even if there are more parts, we only care about the first two. If a folder name lacks the delimiter entirely, Part2 will be empty, resulting in a folder named Part1_. To handle this, you can add conditional checks using if defined Part2 before creating the directory. For more advanced naming conventions, such as handling spaces or special characters, ensure that all variable expansions are enclosed in quotes. This prevents issues with paths containing spaces, which are common in user directories.

Alternative Approaches and Related Tasks

While batch scripting is powerful for simple automation, sometimes you need to perform related operations like renaming existing folders rather than creating new ones. For those scenarios, understanding how to modify directory names directly is essential. You can explore techniques for changing folder names in batch files on Windows 11 Pro to see how ren commands interact with system permissions. Another common requirement is moving content into these newly created structures. If your goal is to organize media files based on their parent folder's name, you might find that moving video files to separate folders by batch script provides a complementary workflow. This allows you to not only create the organizational structure but also populate it automatically. Additionally, if you need to open these newly created folders for verification, you can integrate commands to launch Explorer windows. Effortlessly opening multiple folders and tabs with a batch script can streamline the manual review process after automation completes.

Best Practices for Maintenance

Always test your scripts in a safe, non-production environment first. Use echo commands instead of mkdir initially to verify that the variables are expanding correctly. This "dry run" approach helps identify parsing errors without altering your file system. Furthermore, consider adding logging to your script. Redirecting output to a text file allows you to audit which folders were processed and which new directories were created. This is particularly useful when dealing with large numbers of directories, as it provides a clear record of the operation. By mastering these string manipulation techniques, you gain significant control over file organization tasks. The ability to parse and restructure folder names programmatically saves hours of manual work and reduces the risk of human error in directory management.

Frequently Asked Questions

What happens if a folder name has no delimiter?

If a folder name lacks the specified delimiter, the second token will be empty. Your script should check if the second part exists before attempting to create a folder with an underscore suffix. This prevents the creation of malformed directory names like "Project_".

Can I use this script for files instead of folders?

Yes, but you must change the loop from for /d to for to iterate through files. You will also need to use %%~nxF to get the name and extension, and adjust the parsing logic to account for file extensions if they interfere with your delimiter.

How do I handle spaces in folder names?

Always enclose variable expansions in double quotes, such as "!Part1!_!Part2!". This ensures that the mkdir command treats the entire string as a single path argument, preventing errors caused by spaces being interpreted as separators.

Is it possible to extract more than two parts?

Absolutely. You can increase the number of tokens in the for /f command, such as tokens=1,2,3, and assign additional variables like %%C. This allows you to build more complex folder structures based on multi-part names.

Why does my script fail with special characters?

Special characters like exclamation marks can cause issues if delayed expansion is not enabled. Ensure you have setlocal enabledelayedexpansion at the top of your script and use exclamation marks ! instead of percent signs % for variables inside loops.

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