![](/img/trans.png)
[英]batch file to count all files in a folder and subfolder files and write output file in folder name using batch file
[英]Recursively append folder name to files in it and moves all files to base folder Windows batch file
我想递归地将文件夹(和父文件夹)名称附加到文件夹包含的每个 *.txt 文件。 之后我想将所有文件移动到基本文件夹并删除所有文件夹。 我需要在 Windows BATCH 脚本中实现这一点。 例如:
\BaseFolder\A01\B01\EX1.TXT
\BaseFolder\C01\EX2.TXT
\BaseFolder\EX3.TXT
到:
\BaseFolder\A01-B01-EX1.TXT
\BaseFolder\C01-EX2.TXT
\BaseFolder\EX3.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 循环是:
但这只解决了我目标的一部分。 谁能帮忙?
这是一个“有趣”的想法:
@Set "BaseFolder=C:\Users\Mustafa\BaseFolder"
@ForFiles /P "%BaseFolder%" /S /M *.txt /C "Cmd /C If @IsDir==FALSE For /F 0x22Tokens=*Delims=.\0x22 %%# 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.