我需要一个批处理文件, 对于我放入其中的每个文件夹,找到其名称不在名称列表中的最顶层子目录。
我有这样的文件夹结构:
Presets
|
+--- Author 1
| |
| +--- A1-Library 1
| | |
| | \--- Synth
| |
| \--- A1-Library 2
|
+--- Author 2
| |
| \--- A2-Library 1
|
+--- Library 4
|
\--- Library 5
|
+--- Author 3
| |
| +--- Genre 1
| | |
| | \--- Bass
| |
| \--- Genre 2
|
\--- Author 4
假设我的目录名称列表是
bass
、pad
、synth
,我需要最终得到以下结构:
Presets
|
+--- Author 1
| |
| +--- A1-Library 1
| | |
| | +--- Bass
| | |
| | +--- Synth
| | |
| | \--- Pad
| |
| +--- A1-Library 2
| |
| +--- Bass
| |
| +--- Synth
| |
| \--- Pad
|
+--- Author 2
| |
| \--- A2-Library 1
| |
| +--- Bass
| |
| +--- Synth
| |
| \--- Pad
|
+--- Library 4
| |
| +--- Bass
| |
| +--- Synth
| |
| \--- Pad
|
\--- Library 5
|
+--- Author 3
| |
| +--- Genre 1
| | |
| | +--- Bass
| | |
| | +--- Synth
| | |
| | \--- Pad
| |
| \--- Genre 2
| |
| +--- Bass
| |
| +--- Synth
| |
| \--- Pad
|
\--- Author 4
|
+--- Bass
|
+--- Synth
|
\--- Pad
这就是我现在所做的,主要是通过“聚合”在本网站中找到的答案:
@echo off
setlocal enabledelayedexpansion
:: Check if any arguments were provided to the batch file
if "%~1"=="" (
echo No folders to process.
pause
goto :exit
)
:: Specify the folder names to create
set "folderNames=Bass Pad Synth"
:input_loop
:: Use the first argument as the target folder
set "targetFolder=%~1"
REM ==== THIS SHOULD BE THE LAST SUBFOLDER OF "%~1"
:: Loop through each folder name and create the folders
for %%f in (%folderNames%) do (
md "!targetFolder!\%%f"
)
echo Subfolders created in %targetFolder%
pause
:: Look for the next dropped folder
SHIFT
if "%~1"=="" (
:: Ok, done.
goto :exit
)
goto :input_loop
:exit
如果我删除多个文件夹,在其中创建文件夹,则此批处理有效,并且如果文件夹已存在,则不会显示任何错误。
但是
@ECHO OFF
SETLOCAL
rem that I use for testing and deliberately includes spaces to make sure
rem that the process works using such names. These will need to be changed to suit your situation.
SET "sourcedir=u:\your files"
SET "newleaves=\bass \synth \pad"
:: make a tempfile
:maketemp
SET "tempfile=%temp%\%random%"
IF EXIST "%tempfile%*" GOTO maketemp
(FOR /d /r "%sourcedir%" %%e IN (*) DO ECHO %%e)>"%tempfile%"
FOR /f "delims=" %%e IN ('FINDSTR /v /e /i /l "%newleaves%" "%tempfile%"'
) DO FIND "%%e\" "%tempfile%">nul&IF ERRORLEVEL 1 (
FOR %%y IN (%newleaves%) DO ECHO MD "%%e%%y"
)
DEL "%tempfile%"
GOTO :EOF
在应用于真实数据之前,始终验证测试目录。
所需的 MD 命令仅用于测试目的。
验证命令正确后,将
ECHO
更改为 ECHO MD
以实际创建目录。附加 MD
以抑制错误消息(例如,当目录已存在时)您需要做的就是运行该作业,将每个所需的顶级目录替换为 2>nul
。
首先,创建一个临时文件名。 使用sourcedir
在临时文件中创建递归目录名称列表。
使用
for /d /r
findstr
中不 (/v) 结尾 (/e) 且不区分大小写 (/i) 文字 (/l) 的条目(“新”叶子列表,以空格分隔,每个以反斜杠开头)查找
tempfile
directoryname\
中(这意味着它不是叶子,因为它有子目录),如果该字符串不存在,则创建新的叶子最后,杀死临时文件。
tempfile
将报告错误,可以通过将
md
附加到 2>nul
命令来抑制该错误,如前所述。