搜索文件并返回最匹配的父目录名称?

时间:2019-10-27 12:14:31

标签: batch-file cmd

说我有一个类似"*casting?00*"的搜索掩码,应该与文件名匹配的数量对应于树中的目录。如何仅返回文件名匹配最多的子目录?

2 个答案:

答案 0 :(得分:3)

递归地遍历子文件夹,对每个子文件夹中的匹配文件进行计数(将它们保存到临时文件中以进行进一步处理)。对其进行排序并获得最后一行,将计数器和文件夹名称分开:

String

注意:如果多个文件夹具有相同的最大值。数量的匹配文件,这只会给您最后一个。

编辑以使用数组而不是文件(我认为可读性较差,但只是为了说明如何实现):

@echo off
setlocal enabledelayedexpansion
del tmp.csv 2>nul
for /r /d %%a in (*) do (
set "count="
  for /f %%b in ('dir /b "%%a\*casting?00*" 2^>nul ^|find /c /v ""') do (
  set "count=    %%b"
  echo !count:~-4!,%%a >>tmp.csv
     )
)

sort tmp.csv

for /f "tokens=1,* delims=, " %%a in ('sort tmp.csv') do set "folder=%%b" & set "count=%%a"
echo --- %count% findings in %folder% ---

答案 1 :(得分:0)

我有点道歉,因为我已经劫持了这个问题。这并不是一个竞争性的答案,而是继续使用一系列变量进行讨论。

我的方法可能应该使用术语“伪数组”。我将用文件计数替换传统的增量数组索引。我会将foldername添加到变量名中,以消除重复项。

有很多“陷阱”。在CMD中,这几乎总是正确的。特殊字符会引起问题。使用我将显示的方法,字符"=][肯定会引起问题。另一个问题是命令行的长度和变量名的长度。如果您的路径变得很长,则此代码将阻塞。我认为大约是8,000。

通常,要使数字按字母顺序排序,必须用前导字符(通常为零或空格)填充它们。如果数字是任意的并且是增量的,那么我个人的偏好是从一个大数字开始,例如10000,而不是0或1。但是,在这种情况下,我不是使用增量数字,而是使用文件计数作为伪数字,指数。我更喜欢数学而不是填充零,因此我只增加了1,000,000。只要任何子文件夹中有8,999,999个文件或更少,这将使它保持字母顺序。我敢肯定,CMD数学限制内的最大可能性将从1,000,000,000开始,这大约允许1,147,483,648个文件。

@echo off

setlocal enabledelayedexpansion

:: Just in case there are any array variables already defined
:: we'll clear them first.
for /f "delims==" %%a in ('set a1 2^>nul') do set %%a=
for /f "delims==" %%a in ('set a2 2^>nul') do set %%a=

for /r /d %%a in (*) do (
   for /f %%b in ('dir /b "%%a\*casting?00*" 2^>nul ^|find /c /v ""') do (
      set /a filecount=%%b + 1000000
      set "a1[!filecount!]%%~pnxa=%%b"
      set "a2[%%~a]=%%b"
   )
)

:: Things you can do with this . . .

:: Basic list in order from largest count to smallest
set a1|sort /r

:: List the "first" folder with the most files
echo.
echo The "first" folder with the most files:
for /f "tokens=2 delims==]" %%a in ('set a1 ^| sort /r') do echo %%a & goto :continue

:continue

:: The largest file count
echo.
for /f "tokens=2 delims=[]" %%a in ('set a1 ^| sort /r') do (
   set /a maxfiles = %%a - 1000000
   echo The most files in any subfolder is !maxfiles!.
   goto :continue
)

:continue

:: All of the subfolders that share the max number of files:
echo.
echo.
echo.
for /f "tokens=2 delims=[]=" %%a in ('set a1 ^| sort /r') do (
   set /a maxfiles = %%a - 1000000
   echo All the subfolders with the maximum of !maxfiles! files . . .
   for /f "tokens=2 delims==]" %%b in ('set a1[%%a]') do echo.  %%b
   goto :continue
)

:continue

:: The subfolders with 0 files
echo.
echo.
echo.
echo The subfolders with 0 files . . .
for /f "tokens=2 delims==]" %%a in ('set a1[1000000] 2^>nul') do (
   set nonempty=yes
   echo.  %%a
)
if not defined nonempty echo.  There are none.

:: CSV style output
echo.
echo.
echo.
for /f "tokens=2,3 delims=]=" %%a in ('set a1 ^| sort /r') do echo "%%a",%%b

这里不使用a2数组,而只是一个排列不同的匹配数组的示例。