![批处理脚本用于获取文件夹名称的一部分并从中创建新文件夹](https://linux22.com/image/1629262/%E6%89%B9%E5%A4%84%E7%90%86%E8%84%9A%E6%9C%AC%E7%94%A8%E4%BA%8E%E8%8E%B7%E5%8F%96%E6%96%87%E4%BB%B6%E5%A4%B9%E5%90%8D%E7%A7%B0%E7%9A%84%E4%B8%80%E9%83%A8%E5%88%86%E5%B9%B6%E4%BB%8E%E4%B8%AD%E5%88%9B%E5%BB%BA%E6%96%B0%E6%96%87%E4%BB%B6%E5%A4%B9.png)
我需要编写一个批处理脚本,获取文件夹名称的一部分并
使用该部分名称创建一个新文件夹,然后将原始文件夹移动到其中。
例如:
文件夹“ ABC - DEF
”会得到一个以“ ”为界的新文件夹-
,然后原
文件夹“ ABC
”会ABC - DEF
移入新文件夹“ ”中。
我在编写一个可以与多个文件夹一起执行此操作的脚本时遇到了问题。
我目前拥有的是:
@echo off
C:
cd C:\Folders
setlocal enabledelayedexpansion
for %%A in ('dir /ad /b "C:\Folders*"') do (
echo folder found %%A
for /f "delims=" %%B in ("%%A") do set fname=%%~nB
for /f "delims=" %%C in ("%%A") do set fextn=%%~xC
for /f "tokens=1* delims=-" %%D in ("!fname!") do set
folname=%%D
echo folder name !folname!
if not exist "!folname!" (
echo Folder !folname! does not exist, creating
md "!folname!"
) else (
echo Folder !folname! exists
)
echo Moving file %%A to folder !folname!
move "%%A" "!folname!"
)
echo Finished
pause
答案1
@echo off
cd /d "%~dp0"
setlocal enabledelayedexpansion
for /d %%i in ("* - *") do 2>nul (
echo\ & set "_Folder=%%~i"
echo\Folder found: ...\!_Folder:*\=!
cd /d "%~dp0!_Folder:*- =!\." ) && 2>nul (
echo\Folder "!_Folder:*- =!" exists... & cd.. ) || 2>nul (
echo\Folder: ...\!_Folder:*- =! does not exist, creating...
mkdir "%~dp0!_Folder:*- =!" & echo\Moving file ..\!_Folder:*- =! to folder !_Folder:*- =!
move "%%~fi" "%CD%\!_Folder:*- =!" && echo\Moving file "%%~nxi" to folder "..\!_Folder:*- =!"..
)
)
echo\Finished & %__APPDIR__%timeout.exe -t 60 & endlocal && goto=:EOF
这样做是基于以下假设:
文件夹名称的布局:
ABCspace-space123
该蝙蝠被保存并在将要执行的文件夹中运行:
cd /d "%~dp0"
1.使用cd /d substring
和cd..
验证所需文件夹是否已存在:
cd /d "c:\folder\subfolder\ABC - 123"
cd /d "%~dp0!_Folder:*- =!\." ... cd..
2.使用带有运算符的执行块来接管cd/copy/mkdir
基于以下内容的操作:
return 0
/return non 0
,同时省略任何可能的消息错误2>nul
:cd /d "%~dp0!_Folder:*- =!\." ) && 2>nul ( ↑↑ ⤷ return 0 in last execution, so do: echo\Folder "!_Folder:*- =!" exists... cd.. ) || 2>nul ( ↑↑ ⤷ return non 0 in last execution, so do: echo\Folder: ...\!_Folder:*- =! does not exist, creating... mkdir "%~dp0!_Folder:*- =!" echo\Moving file ..\!_Folder:*- =! to folder