Search code examples
batch-filefor-loopcmdwindownested-loops

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


I'm trying to improve a script posted by @Tony in 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.

To count lines all text file in a directory and subfolders:

  @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

But I'm geting error: "Missing operand."


Solution

  • My bad, I'm was using extra !! in the sentence:

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

    This is the working code:

    @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
    

    [EDITED] as @aschipfl sugested