Every once in a while I get on a computer and I need to count the number of lines in a file. My first instinct is to open my text editor (editplus) and hit ctrl+end to get to the bottom of the document. Then I can view the status bar which will tell me the line number. This works fine when I am on my computer but not when I am on another computer that does not have editplus installed.
My next option might be to open this file in notepad and do the exact same thing. This will work fine if the file is not to large. The problem is I often deal with very large files. I need a quicker way to produce the same results.
This is where DOS comes into play. I can use the following command and let DOS quickly tell me the number of lines in the file.
findstr /R /N "^" file.txt
This command will output every line with a line number in front of it but will still take a long time given a very large file. The solution to this is to take this command one step further.
findstr /R /N "^" file.txt | find /C ":"
Now the output will only be the number of lines that are contained in the file.Again, this command could be taken a step further to tell you how many lines are in the file that contain a certain string.
findstr /R /N "^.*certainString.*$" file.txt | find /c ":"
I’m sure there are many other great uses for find and findstr. If you have found one please post comment.

{ 47 comments… read them below or add one }
I find this to be a very interesting use of findstr and like your website. I recently ran into an issue/limitation with findstr that I did not know existed.
I was trying to find a pattern at a particular column location in the file and it might have been at column position aprox 140. I used the following command
findstr ^…………………………………………………..pattern *.txt>testOutput.txt
In my case there were serveral more periods (single charter wildcard) and I got the error message search string too long.
Is there anyway with findstr to find a pattern at a unique location in a very long line when the pattern is closer to the end of the line?
I think the below searches might help you if I understand the problem correctly.
The below line will find “pattern” anywhere in a line.
findstr /R ".*pattern.*" afile.txtThe below line will find “pattern” after 140 characters.
findstr /r "^(.*){140}pattern.*$" afile.txtHi Brett!
No need for .* in the first example.
findstr /r “pattern” afile.txt
will do. And findstr doesn’t support the () and {} syntax used in the second example, sorry.
What Ken wants to achieve is very difficult using findstr. Maybe if he knew that the pattern always ended five characters before the end of line, he could try something like:
findstr /r “pattern…..$” afile.txt
but that outputs all lines containing a match, not merely all text that matches findstr’s regular expression.
Findstr is frustratingly limited and buggy. Ken would be better off using JavaScript. JS can be embedded inside Batch files (search for “batch javascript hybrid”) so you can have the best of both worlds.
find /c/v "" afile.txtIs the way I figured out how to do it.
@InfinityLoop
The problem with:
find /c /v “” afile.txt
is that it outputs filename as well as number of lines:
find /c /b “” < afile.txt
gets around this by using redirection, but count can be incorrect if file ends with many blank lines.
Either method fails to deal with null characters which the find command outputs as newlines. And additional newlines would cause an incorrect count.
We can open file using dos editor which will show the line numbers you are at.
No need to remember special dos command.
Simply put dos command like
>edit file.txt
Thanks,
Rahul
Liked your line count command line.
findstr /R /N "^" file.txt | find /C ":"I want that if I get 44 lines count from the text file then I do not want to do any thing but if it is greater or less than 44 then Exit Batch file.
Can you help me please.
Thanks
@Rahul: that will not work on 64 bit versions of windows
@Faraz: You can do that in a batch file with something like the following. Just change the name of yourfile.txt and possibly the temp file (save_temp_count.txt):
Brett
Thank you for your prompt reply.
I tested the code, batch file stuck at this below line.
set /p count=
Thanks
@Faraz: Sorry, the code suffered from a bad paste. I have updated the above code.
Let me know if it works for you.
Brett: Brilliant!!! It worked Great. Thank you very much, God bless you & your family.
Works perfect! Thx a lot!
Hi,
thanks a lot for your post, I still have a question:
I want to use this line and store the count result in a variable, can anyone help?
Thanks.
sorry, I read more carefully and this post already have what I needed.
thanks it helped a lot!
Hi Brett,
This below dos code when I run in batch file it Rename all files in Numeric sequence like 1.jpg, 2.jpg, 3.jpg, 4.jpg……. one problem with this code. suppose we have 99 files, When it rename the last file 99.jpg then at the end it again rename 9.jpg to last file like 100.jpg do u have a clue to fix it so it don’t do that or have better dos batch file code to do this task.
===================================================
@echo off
set /a cnt=1
for %%a in (*.jpg) do call :PROCESS “%%a”
goto :EOF
:PROCESS
ren %1 %cnt%.jpg
set /a cnt+=1
===================================================
Thanks
Here’s another example that i found useful:
type *.txt | findstr /R /N “^” | find /C “:”
good for use to count total lines of all the files.
awesome, helped on my uni tutorial, tears since I used dos as mature student
top stuff =)
Nice though, but Google brought me here on a different search. How to display current line number in a batch file (for debugging) ?
Hello,
I have a batch file that counts the number of lines in each text file inside a directory, and then prepends the total number of lines in each file to the beginning of each file in the directory. It looks like this:
@echo off setlocal enabledelayedexpansion cd /d "C:\Users\John\Desktop\Testing\AllFiles" for /f "delims=" %%F in ('dir /b *.txt') do ( for /f "delims=:" %%N in ('findstr /N /R "^" "%%~dpnxF"') do set lines=%%N echo There are !lines! lines in this file > "%%~dpnxF.temp" type "%%~dpnxF">>"%%~dpnxF.temp" del "%%~dpnxF" echo "%%~dpnxF.temp" "%%~nxF" ren "%%~dpnxF.temp" "%%~nxF" )The batch file above works great for small text files in the directory, however, it takes a long time to read the large text files in the directory.
As you stated in your blog, using the code
findstr /R /N “^” file.txt
Does not work well for counting the lines in large text files. So, i added the following code:
findstr /R /N “^” file.txt | find /C “:”
from your blog into the batch file, and now it looks like this:
@echo off setlocal enabledelayedexpansion cd /d "C:\Users\John\Desktop\Testing\AllFiles" for /f "delims=" %%F in ('dir /b *.txt') do ( for /f "delims=:" %%N in ('findstr /N /R "^" "%%~dpnxF" | find /C ":"') do set lines=%%N echo There are !lines! lines in this file > "%%~dpnxF.temp" type "%%~dpnxF">>"%%~dpnxF.temp" del "%%~dpnxF" echo "%%~dpnxF.temp" "%%~nxF" ren "%%~dpnxF.temp" "%%~nxF" )But, when i run the modified code, i get the following error:
“: was unexpected at this time”
Do you know what i am doing wrong?
Thanks in advance :)
I had a need to number a text file before bulk inserting into a database so I could keep the lines in order.
findstr /R /N “^” file.txt >> newfile.txt saved my life…Thanks much.
I wrapped it in a command shell and loaded the file names from SQL and indexed nearly 5,000 text files for a forensic analysis.
This does not work for really big files such as 10 million row. Do you know how to make it work for big files?
@Jadh, I just tried this on a file that had 100 million lines (I added 90 million to your number). I used the following command and it worked perfectly.
findstr /R /N “^” file.txt | find /C “:”
It took a few minutes for it to go through the file but it eventually output 100,000,000. I ran this on Windows 7 64 bit with 8GB memory.
Yup you are right. I was reconciling different records…Thanks for the quick resposne.
Using Brett’s findstr command string, I wrote the following to poll the connection status of my Android device over ADB. The script keeps looping until a device is connected.
echo OFF
:START
adb devices > adb_devices.txt
findstr /R /N “^” adb_devices.txt | find /C “:” > linecount.txt
set /p count=<linecount.txt
if %count% LEQ 2 GOTO START
:END
Hi Brett
I used findstr /R /N “^” test.xml
I renamed test.xml to test.xml1 then also the command worked.
I was expecting command will fail since test.xml is no longer there, but it still worked. Can you please tell me the reason.
It fails for me on Windows 7. I ran the following commands and got an error when I tried to run findstr on a file that did not exist:
Hi,
I want to delete the last 2 lines of the file in DOS.
I do not want to read each line and copy it to a new file. As the file contains thousands of record and it is taking too much time.
Basically i want to copy all the contents of a file except the last 2 lines.
I also have the total number of lines..Just if it makes the task easy.
Please help……
I believe you are going to need a programming language for this. I do not know of a way to do this with the Windows Command Prompt. It could probably be done in Windows Powershell though but that’s not very far from using a programming language.
With a quick Google I found a script someone put together for this using python. I haven’t tested it but you can view the script here.
To count the number of lines in a file why would be do
findstr /R /N “^” file.txt | find /C “:”
Instead one can use
find /C /V “” file.txt
Right?
Also for counting the occurance of particular string in a file what is wrong in using find /C “StringToSearch” file.txt ?
Thanks,
Anupam
I ran a quick test using find /C /V “” file.txt where the file contained the following:
and it produced the output of:
———- TEST.TXT: 5
However, the output should have been greater. Also, the output includes more than just the number.
This is back in 2007 that I put together this command but I suspect I needed only the number. I probably used the number in a batch script for another purpose.
Moreover findstr /R /N “^” file.txt | find /C “:” gives wrong results if there are : in a file which is very common for log files with timestamps.
Actually the command works correctly with files that have colon’s. The reason is that the first part of the command:
Searches file.txt using a regex of ^. Where ^ means the start of the line.
For a file containing the following:
The above part of the command will output:
Then the second part of the command find /C “:” searches on this output which produces 2 as there are exactly two lines with colons in them.
Yes I think you are right. I will check why I was getting wrong results.
i have executed sql file and generated logfile. it has around 80000 lines. But it has 2 empty lines between every two lines.
i have used
findstr /R /N “^.*certainString.*$” filename.txt
but i am get wrong output. mybe because of gap between lines.
so can you give me a fix for this ? and i need to use this command frequently.
@satish – It sounds like you just want to ignore the blank lines. Assuming that there are no spaces or funny characters on the blank lines you could do something like the following:
findstr /N /R “^[^\n]” c:\test.txt | find /c “:”
This will search for and count any line that does not start with a newline character of \n.
Hi Brett,
Thanks so much for your quick reply. following statement has fulfilled my requirement.
The blank lines are ignored when it is searching for the “string” .
thanks for your post.and Happy new year………
Hey, your post is great…I need a help with a script …to find and replace a string in a xml file..preferablly using regular expression.
Your code to find the number of occurance works great,..I need script to find and replace a string…
Can you help ..
Regards
Partha
This…. is awesome. Thanks very much for posting. Just used this on a 4.6m line file (thank goodness)
hi,
i’m greatful if anyody can help me with this issue. i want to get a variable in the 1st line of a txt file and store it in a new variable
aaa.txt
yymmdd 010 xxx
aaa
bbb
I want to open the file, store the seq-no which is 010 to a variable and close the file
Maria, the following commands might work for you. It makes the assumption that you only want to look at the first line and that the sequence number is always the 7th character in and 3 characters long.
Sponge Belly also posted another solution that uses a for loop. I haven’t tested that solution.
Brett-
I am trying to write a batch file to be run in a dos command prompt on XP. I am trying to get a listing of files in a specific path that follow a certain naming convention. I need to copy and rename each file instance to a static name and drop it to a transmission folder. Since it may take a little while for the file to go in the transmission folder, I need to check before I copy the next file over so that I don’t overlay the previous file. I am not able to use SLEEP or TIMEOUT since I don’t have the extra toolkit installed. I try to just continually loop back to a START section until the file is sent. I noticed that if I passed the %%x value set in the for loop that if I loop back to the START section a couple of times, it seems to loose its value and it is set to nothing. So I tried to set a variable to hold the value. I seem to be having issues with the variable not being set correctly or not cleared. Originally it kept on referencing the first file but now it doesn’t seem to be set at all. The ECHO displays the correct the value but the filename variable is empty still. Does anyone know a better way of doing this? Thanks in advance for your help as I have already wasted a whole day on this!
Thanks!!
Kim
@ECHO "At the start of the loop" @for %%x in (C:\OUTBOUND\customer_file*) do ( @ECHO "In the loop" @ECHO "loop value =" @ECHO %%x SET filename=%%x @ECHO "filename =" @ECHO %filename% @ECHO ...ARCHIVE OUTBOUND CUSTOMER FILE archivedatafile --sourcefile="%filename%" --archivefolder="..\archivedata\customer" --retentiondays=0 IF NOT %ERRORLEVEL%==0 GOTO ERROR PAUSE :START IF EXIST l:\OutputFile ( @ping 1.1.1.1 -n 1 -w 30000 GOTO START ) ELSE ( COPY %filename% l:\OutputFile /Y IF NOT %ERRORLEVEL%==0 GOTO ERROR PAUSE ) ) GOTO END :ERROR @echo off @ECHO ************************************************************* @ECHO * !!ERROR!! * @ECHO ************************************************************* :END SET filename=Hi All!
The count will be incorrect if there are null characters in the input to the find command because find outputs them as newlines.
The program below uses only findstr (and some chicanery). It’s fast on large files, copes with extremely long lines, and doesn’t mind if the input file has Windows or Unix line endings.
@echo off & setlocal enableextensions (set lf=^ ) call :LFcount lc "%~1" echo(file "%~1" has %lc% lines endlocal & goto :EOF :LFcount setlocal enabledelayedexpansion findstr /mv "!lf!" "%~2" >nul && ( for /f delims^=: %%n in (' cmd /v:on /c findstr /nv "^!lf^!" "%~2" 2^>nul ') do set lastline=%%n) || (for /f delims^=: %%n in (' (findstr /n "^" "%~2" ^& echo(#^) ^| findstr /bn # 2^>nul ') do set /a lastline=%%n-1) endlocal & set "%1=%lastline%" & exit /b 0For more info, read this blog post: http://wp.me/p2x3If-4i
@Maria
Try this:
@echo off & setlocal enableextensions for /f "usebackq tokens=2" %%s in ("aaa.txt") do ( set seqno=%%s goto break ) :break echo(seq no is %seqno% endlocal & exit /b 0Copy & Paste the above into a file and call it seqno.cmd. Open a Command Prompt in the folder where you saved the file, and type
seqno
on its own and you should see the result. Let me know if you have any more problems.
Hello;
Thanks all for your input, that was helpful to me…
I used this command
To find the total number of lines in all test*.txt files (3 files) but got wrong count (13 Lines)!
Each file has 5 lines (no blank lines at the top, bottom or in the middle)….
Using this command shows why:
Output is:
It is like each last line of a file is counted as one with the first line of the next file???
Any advise how to solve this?
Thanks
A for loop should help with this.
The above command will loop through every file (named test*.txt) and run findstr on each file followed by a newline (echo:). After every file has been processed by findstr then we will count the number of lines.
Thank Brett;
Thats worked very well…
Regards
Thanks for this page. I think you should add multiple strings to this as well.
I did the following to look for XX and YY at the same time: