[英]Gathering list of file extensions - “The command line is too long” workaround
我目前正在使用此批处理文件来扫描Windows文件系统,并保存该系统中所有文件扩展名的.txt文档:
Cmd行命令:
NameOfBatchFile.bat >List.txt
BatchFile代码:
@echo off
set target=%1
if "%target%"=="" set target=%cd%
setlocal EnableDelayedExpansion
set LF=^
rem Previous two lines deliberately left blank for LF to work.
for /f "tokens=*" %%i in ('dir /b /s /a:-d "\\PathOfMyWindowsDirectory"') do (
set ext=%%~xi
if "!ext!"=="" set ext=FileWithNoExtension
echo !extlist! | find "!ext!" > nul
if not !ERRORLEVEL! == 0 set extlist=!extlist!!ext!:
)
echo %extlist::=!LF!%
endlocal
该代码在小型文件夹上效果很好,但是如果我为它提供了一个包含太多子文件夹的文件夹,则命令行将进行处理,然后提供以下错误:
The command line is too long.
The command line is too long.
The command line is too long.
The command line is too long.
The command line is too long.
The command line is too long.
The command line is too long.
The input line is too long.
我无法编辑文件系统以减少子文件夹,有人知道另一种方法来使其工作吗?
您的代码中的问题是变量中元素的串联,这可能会生成一长串扩展名,最终将产生一个冗长的命令行。
@echo off
setlocal enableextensions disabledelayedexpansion
set "target=%~1"
if "%target%"=="" set "target=%cd%"
for /r "%target%" %%a in (*) do if not defined "\%%~xa\" (
if "%%~xa"=="" (echo(FileWithNoExtension) else (echo(%%~xa)
set ""\%%~xa\"=1"
)
endlocal
这通过为每个扩展名设置变量来使用环境存储可见扩展名的信息。 如果未设置该变量,则这是第一次找到扩展并将其回显到控制台。
我认为这是解决此问题的最快方法。
@echo off
setlocal
set target=%1
if "%target%"=="" set target=%cd%
for /R "%target%" %%a in (*.*) do set ext[%%~Xa]=1
for /F "tokens=2 delims=[]" %%a in ('set ext[') do (
if "%%a" equ "=1" (
echo FileWithNoExtension
) else (
echo %%a
)
)
可以很容易地修改先前的方法,以获取具有每个扩展名的文件数 。 只是修改set ext[%%~Xa]=1
由set /A ext[%%~Xa]+=1
和修改令牌for /F
相应。
这样可以非常快速地为您列出所有扩展的列表。
@echo off
set "target=%~1"
if "%target%"=="" set target=%cd%
dir "%target%" /b /s /a-d |repl ".*(\..*)" "$1" |repl ".*\\.*" "FileWithNoExtension"|sort|uniq >file.txt
它使用名为repl.bat
的帮助程序批处理文件(由dbenham提供)-从以下网址下载: https ://www.dropbox.com/s/qidqwztmetbvklt/repl.bat
它使用一个名为uniq.bat
的帮助程序批处理文件(由aacini提供)-从以下位置下载: https ://www.dropbox.com/s/71o38a4ljnqgqjh/uniq.bat
将repl.bat
和uniq.bat
放置在与批处理文件相同的文件夹中或路径上的文件夹中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.