How to find count of lines present in a file using batch script

batchcommand line

I want to count the number of lines in a file using batch.

I have gone through this, but couldn't understand as I am a beginner. I have written my own piece of code with basic knowledge.

@echo off
set "file=abc.csv"
set /a x=0
for /f "usebackq delims=" %%p in ("%file%") do (
  echo %x%
  pause>nul
  set /a x=%x%+1
)

When I run the above code I am getting 0 as output. Can someone please help me in sorting out the error?

Best Answer

I want to count the number of lines in a file using batch

Specific solution

From a command line:

F:\test>for /f "usebackq" %b in (`type abc.csv ^| find "" /v /c`) do @echo line count is %b
line count is 1

From a batch file (countlines.cmd):

@echo off
Setlocal EnableDelayedExpansion
  for /f "usebackq" %%b in (`type abc.csv ^| find "" /v /c`) do (
    echo line count is %%b
    )
  )

Example:

F:\test>countlines
line count is 1
F:\test>

Flexible solution

Use the following batch file (countlines.cmd):

@echo off
Setlocal EnableDelayedExpansion
for /f "usebackq" %%a in (`dir /b /s %1`)  do (
  echo processing file %%a
  for /f "usebackq" %%b in (`type %%a ^| find "" /v /c`) do (
    echo line count is %%b
    set /a lines += %%b
    )
  )
echo total lines is %lines%

Notes:

  • Total number of lines is stored in %lines%.
  • Batch file supports wildcards.
  • Tweak echo ... commands as appropriate.

Usage:

countlines filename_expression

Example:

F:\test>countlines *.csv
processing file F:\test\abc.csv
line count is 1
processing file F:\test\def.csv
line count is 1
total lines is 2

Further Reading

  • An A-Z Index of the Windows CMD command line - An excellent reference for all things Windows cmd line related.
  • dir - Display a list of files and subfolders.
  • find - Search for a text string in a file & display all the lines where it is found.
  • for /f - Loop command against the results of another command.
Related Question