You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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 %%a variable—exactly what you need to get L2021-56378 from your example.
  • Skip the Script: Instead of hardcoding organize, we use if not "%%~fi" == "%~f0" to automatically skip the batch script itself. This makes the script reusable regardless of its own filename.
  • Cleaner Execution: Adding 2>nul to the md command 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 delims setting—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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 17:30:42