我需要编写一个批处理脚本,获取文件夹名称的一部分并
使用该部分名称创建一个新文件夹,然后将原始文件夹移动到其中。
例如:
文件夹“ 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