批处理 - 比较两个 txt 文件

Batch - Comparing two txt files

我在用批处理比较两个 txt 文件时遇到了一些困难。 我使用了具有许多选项匹配的 "findstr" 函数,但 none 有效(例如 FINDSTR /I /V /B /G:file1.txt file2.txt)。 我有第一个 txt 文件如下:

File1.txt

Object 1
Argument 50
Object 2
Argument 10
Object 3
Argument 10
Object 4
Argument 10

第二个文件与第一个文件的开头相同:

File2.txt

Object 1
Argument 50
Object 2
Argument 10
Object 3
Argument 10
Object 4
Argument 10
Object 5
Argument 10
Object 6
Argument 50
Object 7
Argument 10
Object 8
Argument 10

此比较的目的是将第二个文件中重复(仅在同一行)的部分分开。结果必须如下:

File1.txt(不变)

Object 1    
Argument 50        
Object 2
Argument 10
Object 3
Argument 10
Object 4
Argument 10

File2.txt

Object 5
Argument 10
Object 6
Argument 50
Object 7
Argument 10
Object 8
Argument 10

For 循环也许有用... 非常感谢您宝贵的帮助!

如果需要对两个文件进行比较

@echo off
    setlocal enableextensions disabledelayedexpansion

    set "file1=.\file1.txt"
    set "file2=.\file2.txt"

    rem If it is necessary to COMPARE the same lines of the two files
    for %%t in ("%temp%\%~nx0.%random%%random%.tmp") do (
        findstr /n "^" "%file2%" > "%%~ft.2"
        findstr /n "^" "%file1%" > "%%~ft.1"
        findstr /v /l /b /g:"%%~ft.1" "%%~ft.2" > "%%~ft"
        (for /f "usebackq tokens=* delims=0123456789" %%a in ("%%~ft") do (
            set "line=%%a"
            setlocal enabledelayedexpansion
            echo(!line:~1!
            endlocal
        )) > "%file2%.new"
        del /q "%%~ft*"
    )
    type "%file2%.new"

或者,如果 file2 始终是 file1 加上更多行

@echo off
    setlocal enableextensions disabledelayedexpansion

    set "file1=.\file1.txt"
    set "file2=.\file2.txt"

    rem If the only need is to skip the start of the second file 
    rem AND it has less than 65535 lines
    for /f %%a in ('find /v /c "" ^< "%file1%"') do set "nLines=%%a"
    more +%nLines% < "%file2%" > "%file2%.new"
    type "%file2%.new"

下面的代码保留了来自 File2.txt 的第一行与 File1.txt 不同的行:

@echo off
setlocal EnableDelayedExpansion

rem Redirect the *larger* file as input
< File2.txt (

   rem Merge it with lines from shorter file
   for /F "delims=" %%a in (file1.txt) do (

      rem Read the next line from File2
      set /P "line="

      rem If it is different than next line from File1...
      if "!line!" neq "%%a" (

         rem Show this line (the first different one)
         echo !line!
         rem Show the rest of lines from File2
         findstr "^"
         rem And terminate
         goto break

      )
   )

   rem If all lines in File1 were equal to File2, show the rest of File2
   findstr "^"

) > File2_new.txt

:break
move /Y File2_new.txt File2.txt