如何计算目录和子文件夹中所有文本文件的行数

How to count lines all text file in a directory and subfolders

我正在尝试改进@Tony 在 other question

中发布的脚本
  @Echo off
  Set _File=file.txt
  Set /a _Lines=0
  For /f %%j in ('Type %_File%^|Find "" /v /c') Do Set /a _Lines=%%j
  Echo %_File% has %_Lines% lines.

计算目录和子文件夹中所有文本文件的行数:

  @Echo off
  setlocal EnableDelayedExpansion
  Set _Dir=C:\TEST_DIR\
  Set /a _Lines=0
  for /R %_Dir% %%f in (*.*) do (
    for /f %%j in ('Type !%%f!^|Find "" /v /c') Do Set /a _Lines=!_Lines!+!%%j!
  )
  Echo %_Dir% has %_Lines% lines.
  pause

但我收到错误消息:"Missing operand."

糟糕,我在句子中使用了额外的 !!

Do Set /a _Lines=!_Lines!+!%%j!

这是工作代码:

@Echo off
Set _Dir=C:\TEST_DIR\
Set /a _Lines=0
for /R %_Dir% %%f in (*.*) do (
  for /f %%j in ('Find "" /v /c ^< "%%~f"') Do Set /a _Lines=_Lines+%%j
)
Echo %_File% has %_Lines% lines.
pause

[已编辑] 作为@aschipfl sugested

我看到了一些问题。

首先,正如您刚刚在我键入此内容时发现的那样,您得到了丢失的操作数,因为您在 !%%j! 上使用了不需要的延迟扩展。您在 Type !%%f!... 上也不需要它。实际上,它不适用于有空格的文件。我建议将其更改为 Type "%%~f"... 以允许文件名中有空格。

通常,您可以通过使用 echo 查看命令的解释方式来发现这些问题。例如,复制此行,在 Do 之后插入一个 echo。问题变得很明显。

for /f %%j in ('Type !%%f!^|Find "" /v /c') Do echo Set /a _Lines=!_Lines!+!%%j!

此外,请注意,如果您在二进制文件上使用它,您可能会得到意想不到的结果。考虑在 for /r 行中使用不同的文件掩码(或一组文件掩码)而不是 *.*。例如:

for /R %_Dir% %%f in (*.txt *.xml *.ini) do (