Windows count lines in file

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.

When working with files processing via command line on Windows, may need to count lines in a file. It can help to determine how large a given file is. This tutorial shows 2 methods how to count lines in a file on Windows.

In order to test, create a new file:

(echo Line1& echo Line2& echo Line3& echo Line4) > test.txt

Method 1 — CMD

To count lines in a file, use type command to read the content of a file and find command to count lines:

type test.txt | find /c /v ""

Combination of parameters /c and /v in the find command means that need to display a count of the lines that don’t contain the specified string. In our case empty string "".

Method 2 — PowerShell

In PowerShell, the Measure-Object command can be used with -Line parameter in order to count the number of lines:

type test.txt | Measure-Object -Line | %{$_.Lines}

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?

Community's user avatar

asked Apr 28, 2016 at 12:14

learner1's user avatar

3

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.

answered Apr 28, 2016 at 12:57

DavidPostill's user avatar

DavidPostillDavidPostill

154k77 gold badges354 silver badges395 bronze badges

0

A simple way to count the number of lines in a file on a Microsoft Windows system is by using the following command:

find /v /c "" somefile.txt

The /c option counts the number of lines while the /v option displays all lines NOT containing the specified string. Since the null string, i.e. «», is treated as never matching, you should see the number of lines in the file displayed — see the Stupid command-line trick: Counting the number of lines in stdin article at Raymond Chen’s Microsoft Developer Blog, The Old New Thing for an explanation of why this works and how a bug in the earliest MS-DOS version of the find command became a feature that remains to this day. The MS-DOS operating system was an operating system for early PCs provided by Microsoft long before the company created Microsoft Windows.

answered Apr 28, 2016 at 13:14

moonpoint's user avatar

moonpointmoonpoint

5,0802 gold badges19 silver badges22 bronze badges

1

You’re getting count of zero because delayed expansion is turned off.
You’ve already set /a x=0

The value of x inside the for loop doesn’t change with %x%. Replace it with !x!

Try this:

Setlocal EnableDelayedExpansion
@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
)

A simpler way to count the number of lines in a file using batch:

find /v "" /c < abc.csv

answered Mar 14, 2020 at 5:49

Zimba's user avatar

ZimbaZimba

1,06111 silver badges15 bronze badges

1

You must log in to answer this question.

Not the answer you’re looking for? Browse other questions tagged

.

  • Remove From My Forums
  • Question

  • How can I count the number of lines using a batch file?

Answers

  • Try this to count the number of lines in a text file  and display it the way you want …

      set /p =First Query Text: <nul
      Find /V /C «» < c:\Scripts\Example.txt

    Or you can add a string to match and report its count …

      set /p =Count of matching text: <nul
      Find /C «Match string» < c:\Scripts\Example.txt

    The SET /P line acts like an ECHO, but without the newline at the end, so that subsequent text is appended to that line.

    Another approach, which may be more versatile, is to place the result into an environment variable, so that you can use it later in an ECHO or other statement.  The FOR statement with it’s /F switch is used for that …

      for /f %%C in (‘Find /V /C «» ^< c:\Scripts\Example.txt’) do set Count=%%C
      echo The file has %Count% lines.

    Note the carat (^) escape character for the otherwise problematic less than sign (<) within the FORs SET part (the stuff between the parens).  Type FOR/? at a command prompt for more information on this syntax.


    Tom Lavedas

    This completes my question. Thanks a lot!

    • Marked as answer by

      Wednesday, July 27, 2011 12:50 AM

  • Try this to count the number of lines in a text file  and display it the way you want …

      set /p =First Query Text: <nul
      Find /V /C «» < c:\Scripts\Example.txt

    Or you can add a string to match and report its count …

      set /p =Count of matching text: <nul
      Find /C «Match string» < c:\Scripts\Example.txt

    The SET /P line acts like an ECHO, but without the newline at the end, so that subsequent text is appended to that line.

    Another approach, which may be more versatile, is to place the result into an environment variable, so that you can use it later in an ECHO or other statement.  The FOR statement with it’s /F switch is used for that …

      for /f %%C in (‘Find /V /C «» ^< c:\Scripts\Example.txt’) do set Count=%%C
      echo The file has %Count% lines.

    Note the carat (^) escape character for the otherwise problematic less than sign (<) within the FORs SET part (the stuff between the parens).  Type FOR/? at a command prompt for more information on this syntax.


    Tom Lavedas

    • Edited by
      Tom Lavedas
      Tuesday, July 26, 2011 1:17 PM
      to fix minor typos
    • Marked as answer by
      Boe ProxMVP
      Wednesday, July 27, 2011 3:01 AM

Updated: 08/31/2020 by

Many programs and tools provide features to count the number of lines and words, known as line count and word count, in a document. Below are lists of these programs and tools, and instructions on how to get line and word stats.

Online tools

Paste any text into our online text tool to get full statistics on the submitted text. Below are some stats our online tool gives you about your text.

  • First longest word — The first found longest word in your text.
  • First shortest word — The first shortest word in your text.
  • Character count — Total characters in your text.
  • Word count — Total words in your text.
  • Avg word length — The average length of words in your text.
  • Top words — The most common words in your text with no filters.
  • Top non-common words — The most common words with a filter that removes common words like «and» in your text.
  • Sentence count — Total sentences in your text.
  • Longest sentence — The longest sentence in all your text.
  • Avg. sentence length — The average sentence length in your text.
  • Line count — The total lines in your text.
  • Longest line — The longest line found in your text.
  • Vowels — Total vowel count in your text.
  • Consonants — Total consonants in your text.
  • Spaces — Total spaces in your text.
  • Uppercase characters — Total uppercase characters in your text.
  • Lowercase characters — Total lowercase characters in your text.
  • Non-alphanumeric — The number of non-alphanumeric characters in your text.
  • Total Bytes — Total bytes your text requires.
  • Total Bits — The total number of bits your text requires.

Microsoft Windows users

Microsoft Word

Microsoft Word

Users of Microsoft Word can view statistics, such as the number of pages, paragraphs, lines, words, and characters, by following the steps below.

Word 2007 and later

  1. Open Microsoft Word.
  2. Click the Review tab in the Ribbon.
  3. In the Proofing section, click the Word Count option.

Word 2003 and earlier

  1. Open Microsoft Word.
  2. Click File at the top of the window.
  3. Click the Properties option.
  4. In the Properties window, click the Statistics tab.

WordPerfect

Users of Corel WordPerfect can view statistics such as the number of characters, words, sentences, lines, paragraphs, pages, and other document information by following the steps below.

  1. Open WordPerfect.
  2. Click File at the top of the window.
  3. Click the Properties option.
  4. In the Properties window, click the Information tab.

OpenOffice Writer

If you have OpenOffice installed on your computer, it too can display statistics about a file. See the Linux and Unix users section below for steps on getting these stats.

There are also thousands of different text editors available on the Internet, many of them capable of displaying the statistics of a file’s contents.

MS-DOS and Windows command line users

Below are different methods of getting statistical information on files while in MS-DOS.

Find command

Using the find command below lists every line that does not contain «&*fake&*» which in every case is not found. Because this command lists each line containing the string of text, you’d get an accurate list of how many text lines are in the file.

find /v /c "&*fake&*" programs.txt

Edit

Although limited, the edit command can display the number of lines in a file. To do this, follow the steps below.

  1. Edit the file you want to view the line count.
  2. Go to the end of the file. If the file is large, get to the end of the file by pressing Ctrl+End on your keyboard.
  3. Once at the end of the file, the Line: in the status bar displays the line number.

Several third-party MS-DOS utilities also exist designed specifically to count the number of lines in a file and get other statistics.

  • Open an external search for these utilities.

Linux and Unix users

OpenOffice Writer

Users of OpenOffice can view statistics, such as the number of pages, tables, graphics, OLE (Object Linking and Embedding) objects, paragraphs, words, characters, and lines, by following the steps below.

  1. Open OpenOffice Writer.
  2. Click File at the top of the window.
  3. Click the Properties option.
  4. In the Properties window, click the Statistics tab.

From the command line, users have different ways to count and get statistics about files on their computer. Below are a few examples.

wc command — The wc (word count) command is one of the easiest and fastest methods of getting the amount of characters, lines, and words in a file. See this page for additional information and examples of this command.

pico command — Although limited, running the pico command and displaying your current position can give you line and character information. Go to the end of the document and press Ctrl+C or ^C to view the current position and total lines.

vi command and vim command — The vi and vim and its variants can also display the line and character counts.

Also, users can write shell scripts, Perl scripts, or programs to analyze a file’s contents.

  • Windows could not load required file winsetup dll 0x7e
  • Windows could not determine the language to use for setup перевод
  • Windows could not determine the language to use for setup 0x80004005 при обновлении
  • Windows could not determine the language to use for setup 0x80004005 что делать
  • Windows could not determine the language to use for setup 0x80004005 при установке windows 11