递归地将文件夹名称附加到其中的文件,并将所有文件移动到基文件夹 Windows 批处理文件



我想递归地将文件夹(和父文件夹(名称附加到该文件夹包含的每个 *.txt 文件中。之后,我想将所有文件移动到基本文件夹并删除所有文件夹。我需要在Windows BATCH脚本中实现这一点。考考:

BaseFolderA01B01EX1.TXT
BaseFolderC01EX2.TXT
BaseFolderEX3.TXT

自:

BaseFolderA01-B01-EX1.TXT
BaseFolderC01-EX2.TXT
BaseFolderEX3.TXT

为此,多亏了JosefZ,我找到了这个解决方案:

递归地将文件夹名称附加到 Windows 批处理文件中的文件

@echo OFF
SETLOCAL EnableExtensions
for /F "delims=" %%G in ('dir /B /S "C:Source*.txt"') do (
for %%g in ("%%~dpG.") do rename "%%~fG" "%%~nxg_%%~nxG"
)
pause

其中 FOR 循环是:

  • 外部 %%G 循环创建.txt文件的静态列表(递归(,并且
  • 内部 %%g 循环获取每个特定文件的父文件夹。

但这只能解决我目标的一部分。谁能帮忙?

这是一个"有趣"的想法:

@Set "BaseFolder=C:UsersMustafaBaseFolder"
@ForFiles /P "%BaseFolder%" /S /M *.txt /C "Cmd /C If @IsDir==FALSE For /F 0x22Tokens=*Delims=.x22 %%# In (@RelPath)Do @If Not 0x22%%#0x22==@File Set 0x22_=%%#0x22&Call Move /Y 0x22%BaseFolder%%%#0x22 0x22%BaseFolder%%%_:=-%%0x22>NUL"

请注意,此未经测试的解决方案很可能具有命令行长度限制。因此,如果您的初始基本文件夹位于卷的深处和/或其树很深或带有长文件和目录名称,我会避免使用它。鉴于该警告信息,请记住根据需要调整第一行的完整路径值。

以下脚本应该完成您想要的,即按预定义移动和重命名文件并删除剩余的空子目录(请参阅所有解释性rem注释(:

@echo off
setlocal EnableExtensions DisableDelayedExpansion
rem // Define constants here:
set "_ROOT=.BaseFolder" & rem // (target base directory)
set "_MASK=*.txt"        & rem // (file search pattern)
set "_CHAR=-"            & rem // (separator character)
rem // Switch to target directory:
pushd "%_ROOT%" && (
rem // Loop through list of relative paths of matching files:
for /F "tokens=1* delims=:" %%E in ('
xcopy /L /S /I "%_MASK%" "%TEMP%" ^| find ":"
') do (
rem // Store current relative file path, initialise variables:
set "FILE=%%F" & set "NAME=" & set /A "NUM=0"
rem // Toggle delayed expansion to avoid trouble with `!` and `^`:
setlocal EnableDelayedExpansion
rem // Loop through all individual elements of file relative path:
for %%I in ("!FILE:=" "!") do (
endlocal
rem // Store current path element and count them:
set "ITEM=%%~I" & set /A "NUM+=1"
setlocal EnableDelayedExpansion
rem // Build new file name and pass it over `endlocal` barrier:
for /F "delims=" %%N in ("!NAME!%_CHAR%!ITEM!") do (
endlocal
set "NAME=%%N"
setlocal EnableDelayedExpansion
)
)
rem // Finalise new file name:
if defined _CHAR set "NAME=!NAME:*%_CHAR%=!"
rem // Actually move and rename the current file:
> nul move "!FILE!" "!NAME!"
rem // Switch to parent directory of current file:
pushd "!FILE!.." && (
rem // Loop through parent directory elements:
for /L %%N in (2,1,!NUM!) do (
rem // Try to remove parent directory when empty, go one up:
set "DD=!CD!" & cd ".." & 2> nul rd "!DD!"
)
rem // Return to previous working directory:
popd
)
endlocal
)
rem // return to original working directory:
popd
)
endlocal
exit /B

最新更新