How to count no of lines in text file and store the value into a variable using batch script?

前端 未结 16 1216
青春惊慌失措
青春惊慌失措 2020-11-27 14:28

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         


        
16条回答
  •  死守一世寂寞
    2020-11-27 15:15

    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.

提交回复
热议问题