[英]Trying to Get A Line Count for all Files in a Directory and Sub-Directories using a Bat File
I am trying to get this bat file i am working on to provide me with a list of documents in a directory (and all of the sub-directories) and the line counts per document. 我正在尝试获取此bat文件,以便为我提供目录(以及所有子目录)中的文档列表以及每个文档的行数。
I have been able to get the code below to work but it only provides me the documents in the root of the folder, none of the sub-directories. 我已经能够获取下面的代码,但是它只为我提供文件夹根目录中的文档,而没有子目录。 I've searched so many different forums but have been unable to find a workable answer. 我搜索了很多不同的论坛,但一直找不到可行的答案。
@echo off
:start
cls
echo Enter full path to directory that you want to count files for:
set /P FilePath=
echo ..
echo ...
if exist %FilePath%\CountLines.csv del %FilePath%\CountLines.csv /q
for /f "usebackq delims=" %%a in (`find /v /c "" "%FilePath%"\*.*`) do echo %%a >> "%FilePath%"\CountLines.csv
pause()
goto start
This is the output i get, which is correct but its not returning docs in the sub-directories 这是我得到的输出,这是正确的,但在子目录中未返回文档
MD5HASH APPEARS ONCE.csv 1174690
Split.txt 4258
COUNTLINESINFILES.txt 1
@echo off
setlocal
echo Enter full path to directory that you want to count files for:
rem Get path of the directory to search.
set /P "FilePath=" || (
>&2 echo Invalid reply.
exit /b 1
)
rem Check if the dir path exists.
if not exist "%FilePath%\" (
>&2 echo Invalid path.
exit /b 1
)
echo ..
echo ...
rem Get count of lines of files in the dir path.
(
for /r "%FilePath%" %%A in (*) do (
find /v /c "" "%%~A"
)
) > "%FilePath%\CountLines.csv"
echo Results:
type "%FilePath%\CountLines.csv"
pause
If setting variables in a script, setlocal
can help to keep the variables local to the script. 如果在脚本中设置变量,则setlocal
可以帮助将变量保持在脚本本地。 setlocal
has been added. setlocal
已添加。
Consider that if the user presses return , without entering anything, then that can be a invalid path else a path starting with a single backslash can be interpreted as from the root of a drive. 请考虑一下,如果用户按return键 ,而不输入任何内容,则该路径可能是无效路径,否则可以将以单个反斜杠开头的路径解释为从驱动器的根目录开始。 I do not consider the user may consider that so the ||
我不认为用户可能会认为||
is a failure check, and executes the parenthesed code if it is a failure. 是失败检查,如果失败则执行括号中的代码。
Check if the replied path is valid before continuing. 在继续之前,请检查所回复的路径是否有效。
The for /r
loop will iterate recursively with the pattern of *
. for /r
循环将使用*
模式进行递归迭代。 find
will read each file and the stdout is written to file. find
将读取每个文件,并将stdout写入文件。 With the whole for /r
within parentheses, allows all stdout to be written to file before closing the file handle. 在for /r
的整个括号内,允许在关闭文件句柄之前将所有stdout写入文件。
The results are shown at the end by using type
. 结果使用type
显示在最后。
See for /?
看到for /?
for help with understanding for /r
and all the other types of for
loops. 帮助您了解for /r
以及所有其他类型的for
循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.