如何在Windows批处理中分割字符串?优化批量文件整理代码
Batch Script: Split Filenames & Organize Files into Folders by First Token
Got it, let's tweak your script to extract the first segment of each filename (like L2021-56378 from L2021-56378 Sample Documentation Form) and use that as the folder name. Here's the adjusted code with clear explanations:
Modified Working Script
@echo off setlocal :: Loop through every file in the current directory for %%i in (*) do ( :: Skip the script itself (works no matter what you name the batch file) if not "%%~fi" == "%~f0" ( :: Split the filename (without extension) by spaces, grab the first part for /f "tokens=1 delims= " %%a in ("%%~ni") do ( :: Create the folder (suppress error if it already exists) md "%%a" 2>nul :: Move the file into the target folder move "%%~i" "%%a\" ) ) ) endlocal
Key Improvements & Explanations
- Filename Splitting: The
for /f "tokens=1 delims= " %%a in ("%%~ni")line is the magic here. It takes the filename without its extension (%%~ni), splits it using spaces as separators, and captures the first segment into the%%avariable—exactly what you need to getL2021-56378from your example. - Skip the Script: Instead of hardcoding
organize, we useif not "%%~fi" == "%~f0"to automatically skip the batch script itself. This makes the script reusable regardless of its own filename. - Cleaner Execution: Adding
2>nulto themdcommand hides the annoying "folder already exists" error message, so the script runs smoothly even if some folders are already present. - Safe File Move: The trailing backslash in
move "%%~i" "%%a\"ensures we're moving the file into the folder, not accidentally renaming it to match the folder name (avoids conflicts if a file with the folder name exists).
Quick Notes
- If your filenames have leading spaces that you need to preserve, you'd need to adjust the
delimssetting—but your example doesn't include this, so it's not necessary here. - Just run this script directly from the folder where your target files are stored, and it'll handle the rest.
内容的提问来源于stack exchange,提问作者Scalestwoseven
相关产品推荐
相关产品推荐

