计算第一行和最后一行之间的行数,并将该计数与另一个值进行比较

时间:2015-07-07 08:20:48

标签: file batch-file

我有一个像

这样的文本文件
  

0000062015< ----第一行   EEE
  EEE
  EEE
  C EEE
  C EEE
  EEE
  结束< -----最后一行

  1. 脚本是读取第1行并获得前6位

  2. 然后计算从第2行到第END行之前的行数(应该有6行,因为第一行的前六位数字形成数字000006),然后比较这两个数字是否相同。

  3. 我知道我可以使用

    @echo off
    cls
    setlocal EnableDelayedExpansion
    set "cmd=findstr /R /N "^^" 20150629_eleave_i_test.txt | find /C ":""
    
    for /f %%a in ('!cmd!') do set number=%%a
    echo %number%
    

    计算此文件中的所有行,但我不知道从第一行提取我想要的子字符串,或者如何比较这两个数字。

    任何提示?

3 个答案:

答案 0 :(得分:0)

@echo off
setlocal enabledelayedexpansion
cls

:: If your text file isn't in the same directory as your script, you need
:: to add the full path to the file instead.
set "text_file=20150629_eleave_i_test.txt"

:: Get the first six characters of the first line of the text file
set /p first_six=<%text_file%
set first_six=!first_six:~0,6!

:: Remove the leading zeroes
set /a first_six=1!first_six!-1000000

:: Count the number of lines in the text file, then subtract two
:: because we're not counting the first or last lines
set count=0
for /F %%A in (%text_file%) do set /a count+=1
set /a count=!count!-2

if !count! equ !first_six! (
    echo Values match
) else (
    echo Values do not match
)
pause

答案 1 :(得分:0)

@echo off
    setlocal enableextensions disabledelayedexpansion

    Rem For each txt file in current folder
    for %%f in (*.txt) do (

        Rem Retrieve the first line and the number of lines in the file
        Rem and prepare the data for later compare
        for /f "tokens=1,2 delims==" %%a in ('
            ^< "%%~ff" ( 
                set /p "nLines="
                ^& set nLines
                ^& find /c /v ""
            ^)
        ') do if "%%b"=="" (set /a "count=1000000+%%a-2") else (set "nLines=%%b")

        Rem Check if both values are equal or not
        setlocal enabledelayedexpansion
        for /f "tokens=1-2" %%a in ("1!nLines:~0,6! !count!") do (
            endlocal
            if "%%a" equ "%%b" ( 
                echo OK  - %%f
            ) else ( 
                echo BAD - %%f
            )
        )
    )

答案 2 :(得分:0)

编辑根据评论中的要求修改了代码

@echo off
setlocal

set filename=textFile.txt

rem Read number of lines from first line in file
set /p number=< "%filename%"
set /A number=1%number:~0,6% - 1000000

rem Get the number of lines-2 and the last line via findstr /N
for /F "tokens=1* delims=:" %%a in ('findstr /N "^" "%filename%"') do (
   set /A count=%%a-2
   set "lastLine=%%b"
)

if "%lastLine%" neq "END" (
   echo The last line is not "END"
)

if %number% equ %count% (
   echo Numbers are the same
) else (
   echo Different numbers
)