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

前端 未结 16 1247
青春惊慌失措
青春惊慌失措 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:03

    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.

提交回复
热议问题