使用批处理文件计算每个文本文件的行数

时间:2017-07-21 16:09:26

标签: windows batch-file for-loop cmd md5

我有这个批处理命令,它计算每个日志/文本文件的行数。如果我有一个包含3行或更多行的文本文件,这意味着我的md5deep验证不匹配。问题是我有多个CheckMismatch.txt文件夹。我正在寻找一个循环,它将检查所有CheckMismatch.txt并逐个计算行。

IF EXIST C:\BACKUPS\WEBAPP-UAT\WEBAPP\FOLDER1 (md5deep64 -x "C:\BACKUPS\WEBAPP-UAT\WEBAPP\FOLDER1\FOLDER1.md5" -r "C:\BACKUPS\WEBAPP-UAT\WEBAPP\FOLDER1" > C:\BACKUPS\WEBAPP-UAT\WEBAPP\FOLDER1\CheckMismatch.txt
@echo off
setlocal EnableDelayedExpansion
set "cmd=findstr /R /N "^^" C:\BACKUPS\WEBAPP-UAT\WEBAPP\FOLDER1\CheckMismatch.txt | find /C ":""
for /f %%a in ('!cmd!') do set number=%%a
if %number% gtr 2 (echo there is a mismatch in FOLDER1) ELSE (echo FOLDER1 HASHES matched)
)
  1. Folder1中 CheckMismatch.txt
  2. FOLDER2 CheckMismatch.txt
  3. Folder3 CheckMismatch.txt
  4. Folder4 CheckMismatch.txt
  5. Folder5 CheckMismatch.txt

2 个答案:

答案 0 :(得分:1)

FINDSTR之前无需FIND。您可以仅使用FIND直接计算行数。您可以使用FINDSTR来测试计数是否小于或等于2.这使您可以使用&&||代替IF

如果您要在"C:\BACKUPS\WEBAPP-UAT\WEBAPP\"

下处理固定的文件夹列表
@echo off
setlocal
set "root=C:\BACKUPS\WEBAPP-UAT\WEBAPP"
for %%F in (
  Folder1
  Folder2
  Folder3
  Folder4
  Folder5
) do (
  md5deep64 -x "%root%\%%F\%%F.md5" -r "%root%\%%F" >"%root%\%%F\CheckMismatch.txt"
  type "%root%\%%F\CheckMismatch.txt" | find /c /v "" | findstr /x "0 1 2" && (
    echo There is a mismatch in %%F
  ) || (
    echo %%F hashes matched
  )
)

您更有可能要处理"C:\BACKUPS\WEBAPP-UAT\WEBAPP\"

下的所有文件夹
@echo off
for /d %%F in ("C:\BACKUPS\WEBAPP-UAT\WEBAPP\*") do (
  md5deep64 -x "%%F\%%~nxF.md5" -r "%%F" >"%%F\CheckMismatch.txt"
  type "%%F\CheckMismatch.txt" | find /c /v "" | findstr /x "0 1 2" && (
    echo %%~nxF hashes matched
  ) || (
    echo There is a mismatch in %%~nxF
  )
)

如果CheckMismatch.txt只是您以后不需要的临时文件,那么您可以完全避免创建该文件

@echo off
for /d %%F in ("C:\BACKUPS\WEBAPP-UAT\WEBAPP\*") do (
  md5deep64 -x "%%F\%%~nxF.md5" -r "%%F" | find /c /v "" | findstr /x "0 1 2" && (
    echo %%~nxF hashes matched
  ) || (
    echo There is a mismatch in %%~nxF
  )
)

答案 1 :(得分:0)

存在延迟扩展问题(在代码块中使用%number%而不是!number!
试图更清晰地格式化。

@Echo off
SetLocal EnableExtensions EnableDelayedExpansion
Set "Folder=C:\BACKUPS\WEBAPP-UAT\WEBAPP\FOLDER1
IF EXIST "%Folder%" (
    md5deep64 -x "%Folder%\FOLDER1.md5" ^
              -r "%Folder%" > "%Folder%\CheckMismatch.txt"
    set "cmd=findstr /R /N "^^" "%Folder%\CheckMismatch.txt" | find /C ":""
    Set "number=0"
    for /f %%a in ('!cmd!') do set number=%%a

    if !number! gtr 2 (
        echo there is a mismatch in FOLDER1
    ) ELSE (
        echo FOLDER1 HASHES matched)
    )
)