Number of files in a directory

2019-08-24 02:14发布

问题:

I'm try to find, in only one row, the number of files (*.rar) in a directory.

For doing this I'm using the commands:

for /f "delims=" %i in ('find /c ".rar" "D:\backup e ckpdb ept-icd\test\unload\lista_files_rar.txt"') do echo %i

but the value of %i I have at the end is : D:\BACKUP E CKPDB EPT-ICD\TEST\UNLOAD\LISTA_FILES_RAR.TXT: 8

I would like to obtain only the number 8 so instead to echo the value I would assign the value to a variable.

I use the command line : dir /b *.rar | find /c ".rar" that it returns the value of rar files in the directory, but I can't assign the value to a variable, for example: dir /b *.rar | find /c ".rar" | set/a files =

I tried also to use the keyword tokens=2 but it doesn't work

p.s If it possible to do it only with the find command is also better

回答1:

See here for example on counting files

Or you can simply do something like this (not tested)

for /F %%j in ('dir /B *.rar ^| find /C /V ""') do set count=%%j


回答2:

This returns just the number; there might be a cleaner way to do it, but unfortuantly "find" can't take it's input from a pipe (i.e., I can't do dir | find):

@echo off
dir /b *.rar> out.tmp
for /f "usebackq tokens=3" %%i in (`find /c "rar" out.tmp`) do echo %%i
del out.tmp


回答3:

Try "delims=: tokens=3"

You normally will have two colons in the result, one after the drive letter and one before the number you want, so your number should be token 3



回答4:

Thank you, I think I will use

for /F %%j in ('dir /B *.rar ^| find /C /V ""') do set count=%%j

user135127

In this way I think also if somethink in the name of the dir the result should remain always the same.

which is the difference between :

dir /B *.rar ^| find /C /V "" and

dir /B *.rar ^| find /C ".rar" ?



回答5:

for /f %a in ('dir "*.txt" ^| find "File(s)"') do set Count=%a

Gives

set Count=36

or you can use an arithmetic set and delayed environment variable expansion

set count=0
for %a in (*.txt) do @set /a Count=!Count!+ 1 > nul
echo %count%

gives

Count=36