Count number of lines in a file using DOS


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.



Related Posts:

4 Responses to “Count number of lines in a file using DOS”

  1. Ken Happich
    Ken Happich Says:

    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?

  2. Brett Batie
    Brett Says:

    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.txt

    The below line will find “pattern” after 140 characters.
    findstr /r “^(.*){140}pattern.*$” afile.txt

  3. iNFiNiTyLoOp
    iNFiNiTyLoOp Says:

    find /c/v “” afile.txt
    Is the way I figured out how to do it.

  4. Rahul Babar
    Rahul Babar Says:

    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

Leave a Reply