将两个txt文件与批处理进行比较时遇到一些困难。 我使用了" findstr"具有许多选项匹配的函数但不起作用(例如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循环可能有用...... 非常感谢您的宝贵帮助!
答案 0 :(得分:2)
如果两个文件之间的比较是必要的
@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"
答案 1 :(得分:2)
下面的代码保留第一行中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