47

I want to count the no of lines in a text file and then the value has to be stored into a environment variable. The command to count the no of lines is

findstr /R /N "^" file.txt | find /C ":"

I refered the question How to store the result of a command expression in a variable using bat scripts? Then I tried,

set cmd="findstr /R /N "^" file.txt | find /C ":" "

I am getting the error message,

FIND: Parameter format not correct

How could i get rid of this error.

14 Answers 14

35

You could use the FOR /F loop, to assign the output to a variable.

I use the cmd-variable, so it's not neccessary to escape the pipe or other characters in the cmd-string, as the delayed expansion passes the string "unchanged" to the FOR-Loop.

@echo off
cls
setlocal EnableDelayedExpansion
set "cmd=findstr /R /N "^^" file.txt | find /C ":""

for /f %%a in ('!cmd!') do set number=%%a
echo %number%
  • Thanks a ton for this, I used it in "questions/1350225" and it worked perfectly! – SuperMar1o Jul 18 '13 at 3:50
  • 2
    Thanks a lot! I just tried it here to count the lines on ALL files within a directory and it worked fine too. Just replace file.txt to *.txt and wait. :) – Christian Dechery Mar 21 '14 at 12:34
88

There is a much simpler way than all of these other methods.

find /v /c "" filename.ext

Holdover from the legacy MS-DOS days, apparently. More info here: https://devblogs.microsoft.com/oldnewthing/20110825-00/?p=9803

Example use:

adb shell pm list packages | find /v /c ""

If your android device is connected to your PC and you have the android SDK on your path, this prints out the number of apps installed on your device.

  • 4
    that doesn't meet the requirement to store the value in an environment variable. – ChrisJJ Aug 26 '14 at 14:54
  • 1
    clean and quite efficient. nice. – habitats Feb 22 '16 at 0:11
  • 2
    @ChrisJJ if you set up a subroutine (or .bat) that just does :SET __ for /f "tokens=*" %%A in ('%2 %3 %4 %5 %6 %7 %8 %9') do Set "%1=%%A" __ Exit \B you can save any one-line-output program to a var just by calling it like so; Call :SET varName find /v /c "" filename.ext (where __ is a newline) – Hashbrown Aug 4 '16 at 7:31
  • 1
    I don't know why this answer has so many upvotes. The earlier responses included the same find command but also provided the count in a variable as requested. – Tony Oct 22 '16 at 0:15
  • 1
    To get the result in variable LINE, use for /F "usebackq tokens=3 delims=:" %%L in (`find /v /c "" %logfile%`) do set lines=%%L – Joe Dec 15 '18 at 19:38
-1

The perfect solution is:

FOR /F %%i IN ('TYPE "Text file.txt" ^| FIND /C /V ""') DO SET Lines=%%i
  • It's a good solution, but the same answer was given already many times for this question. The oldest, equal answer is from 2012 – jeb Dec 6 '18 at 15:23
  • but the more simply and logic. – Riccardo La Marca Dec 6 '18 at 15:26
1

Just:

c:\>(for /r %f in (*.java) do @type %f ) | find /c /v ""

Font: https://superuser.com/questions/959036/what-is-the-windows-equivalent-of-wc-l

3

You don't need to use find.

@echo off
set /a counter=0
for /f %%a in (filename) do set /a counter+=1
echo Number of lines: %counter%

This iterates all lines in the file and increases the counter variable by 1 for each line.

  • But it doesn't count empty lines and lines starting with semi colon – jeb Mar 6 '18 at 18:27
0

The :countLines subroutine below accepts two parameters: a variable name; and a filename. The number of lines in the file are counted, the result is stored in the variable, and the result is passed back to the main program.

The code has the following features:

  • Reads files with Windows or Unix line endings.
  • Handles Unicode as well as ANSI/ASCII text files.
  • Copes with extremely long lines.
  • Isn’t fazed by the null character.
  • Raises an error on reading an empty file.
  • Counts beyond the Batch max int limit of (31^2)-1.
@echo off & setLocal enableExtensions disableDelayedExpansion

call :countLines noOfLines "%~1" || (
    >&2 echo(file "%~nx1" is empty & goto end
) %= cond exec =%
echo(file "%~nx1" has %noOfLines% line(s)

:end - exit program with appropriate errorLevel
endLocal & goto :EOF

:countLines result= "%file%"
:: counts the number of lines in a file
setLocal disableDelayedExpansion
(set "lc=0" & call)

for /f "delims=:" %%N in ('
    cmd /d /a /c type "%~2" ^^^& ^<nul set /p "=#" ^| (^
    2^>nul findStr /n "^" ^&^& echo(^) ^| ^
    findStr /blv 1: ^| 2^>nul findStr /lnxc:" "
') do (set "lc=%%N" & call;) %= for /f =%

endlocal & set "%1=%lc%"
exit /b %errorLevel% %= countLines =%

I know it looks hideous, but it covers most edge-cases and is surprisingly fast.

0

You can pipe the output of type into find inside the in(…) clause of a for /f loop:

for /f %%A in ('
    type "%~dpf1" ^| find /c /v ""
') do set "lineCount=%%A"

But the pipe starts a subshell, which slows things down.

Or, you could redirect input from the file into find like so:

for /f %%A in ('
    find /c /v "" ^< "%~dpf1"
') do set "lineCount=%%A"

But this approach will give you an answer 1 less than the actual number of lines if the file ends with one or more blank lines, as teased out by the late foxidrive in counting lines in a file.

And then again, you could always try:

find /c /v "" example.txt

The trouble is, the output from the above command looks like this:

---------- EXAMPLE.TXT: 511

You could split the string on the colon to get the count, but there might be more than one colon if the filename had a full path.

Here’s my take on that problem:

for /f "delims=" %%A in ('
    find /c /v "" "%~1"
') do for %%B in (%%A) do set "lineCount=%%B"

This will always store the count in the variable.

Just one last little problem… find treats null characters as newlines. So if sneaky nulls crept into your text file, or if you want to count the lines in a Unicode file, this answer isn’t for you.

3
for /f "usebackq" %A in (`TYPE c:\temp\file.txt ^| find /v /c "" `) do set numlines=%A

in a batch file, use %%A instead of %A

9

Try this:

@Echo off
Set _File=file.txt
Set /a _Lines=0
For /f %%j in ('Find "" /v /c ^< %_File%') Do Set /a _Lines=%%j
Echo %_File% has %_Lines% lines.

It eliminates the extra FindStr and doesn't need expansion.


- edited to use ChrisJJ's redirect suggestion. Removal of the TYPE command makes it three times faster.

  • 1
    Thanks. That gets my vote :) . But I find the type command is not needed. For /f %%j in ('Find "" /v /c ^< %_File%') Do Set /a _Lines=%%j – ChrisJJ Aug 26 '14 at 15:05
  • Hi ChrisJJ, your usage of the < and my TYPE | equate to the same thing. – Tony Aug 26 '14 at 15:51
  • < amounts to one less command... FWIW :) – ChrisJJ Aug 27 '14 at 13:24
0

In the below code, the variable name are SalaryCount and TaxCount

@ECHO OFF    
echo Process started, please wait...    
for /f %%C in ('Find /V /C "" ^< "D:\Trial\Salary.txt"') do set SalaryCount=%%C    
echo Salary,%SalaryCount%
for /f %%C in ('Find /V /C "" ^< "D:\Trial\Tax.txt"') do set TaxCount=%%C
echo Tax,%TaxCount%

Now if you need to output these values to a csv file, you could use the below code.

@ECHO OFF
cd "D:\CSVOutputPath\"
echo Process started, please wait...
echo FILENAME,FILECOUNT> SUMMARY.csv
for /f %%C in ('Find /V /C "" ^< "D:\Trial\Salary.txt"') do set Count=%%C
echo Salary,%Count%>> SUMMARY.csv
for /f %%C in ('Find /V /C "" ^< "D:\Trial\Tax.txt"') do set Count=%%C
echo Tax,%Count%>> SUMMARY.csv

The > will overwrite the existing content of the file and the >> will append the new data to existing data. The CSV will be generated in D:\CSVOutputPath

16

Inspired by the previous posts, a shorter way of doing so:

CMD.exe
C:\>FINDSTR /R /N "^.*$" file.txt | FIND /C ":"

The number of lines

Try it. It works in my console.

EDITED:

(the "$" sign removed)

FINDSTR /R /N "^.*" file.txt | FIND /C ":"

$ reduces the number by 1 because it is accepting the first row as Field name and then counting the number of rows.

  • this gives a lot of errors if the file has very lone lines, however the final output is still correct – habitats Feb 22 '16 at 0:12
2

I found this solution to work best for creating a log file that maintains itself:

setlocal enabledelayedexpansion
SET /A maxlines= 10
set "cmd=findstr /R /N "^^" "filename.txt" | find /C ":""
 for /f %%a in ('!cmd!') do set linecount=%%a
GOTO NEXT

:NEXT 
 FOR /F %%A IN ("filename.txt") DO ( 
  IF %linecount% GEQ %maxlines% GOTO ExitLoop
  echo %clientname% %Date% %Time% >> "filename.txt")
 EXIT

:ExitLoop
 echo %clientname% %Date% %Time% > "filename.txt"
 EXIT

Environmental variables included are %clientname% the computername of the remote client %Date% is the current date and %Time% the current time. :NEXT is called after getting the number of lines in the file. If the file line count is greater than the %maxlines% variable it goes to the :EXITLOOP where it overwrites the file, creating a new one with the first line of information. if it is less than the %maxlines% variable it simply adds the line to the current file.

4

I usually use something more like this for /f %%a in (%_file%) do (set /a Lines+=1)

  • slow for large files and doesn't count empty lines (they are ignored by for /f so the counter doesn't increase) – Stephan May 30 at 10:26
4

@Tony: You can even get rid of the type %file% command.

for /f "tokens=2 delims=:" %%a in ('find /c /v "" %_file%') do set /a _Lines=%%a

For long files this should be even quicker.

  • 1
    This is faster, but with this approach, if the file name contains a colon (for instance, "c:\temp\file.txt"), it's parsing that string at the colon instead of the result of the command. – Tony Mar 27 '13 at 12:47
  • for %%a in ("%file%") do for /f "tokens=3 delims=:" %%b in ('find /v /c "" "%%~fa"') do set lines=%%b handles short and long file names. – jwalker Jan 22 '15 at 16:00

protected by eyllanesc Jul 21 '18 at 4:48

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.