0

我有两个文本文件,file1 和 file2。我想确定 file2 中的哪些行在 file1 中不存在。如何使用 DOS 批处理文件执行此操作?

4

2 回答 2

1
findstr /v /g:file1 file2

使用 findstr,表示要匹配的字符串应该取自 file1,在 file2 中搜索,以显示 file2 中与 file1 中的字符串不匹配的行

于 2013-11-15T09:48:47.117 回答
0

下面的批处理文件假定任何文件中都没有空行。

@echo off
setlocal EnableDelayedExpansion

< file2 (
   set /P line2=
   for /F "delims=" %%a in (file1) do (
      set "line1=%%a"
      call :SeekNextLineInFile2ThatMatchThisLineInFile1
   )
   set "line1="
   call :SeekNextLineInFile2ThatMatchThisLineInFile1
)
goto :EOF

:SeekNextLineInFile2ThatMatchThisLineInFile1
   if not defined line2 exit /B
   if "!line2!" equ "%line1%" goto lineFound
   echo !line2!
   set "line2="
   set /P line2=
goto SeekNextLineInFile2ThatMatchThisLineInFile1
:lineFound
set "line2="
set /P line2=
exit /B

文件1:

First line in both files
Second line in both files
Third line in both files
Fourth line in both files
Fifth line in both files

文件2:

First line in file2 not in file1
First line in both files
Second line in both files
Second line in file2 not in file1
Third line in file2 not in file1
Third line in both files
Fourth line in both files
Fourth line in file2 not in file1
Fifth line in file2 not in file1
Fifth line in both files
Sixth line in file2 not in file1

输出:

First line in file2 not in file1
Second line in file2 not in file1
Third line in file2 not in file1
Fourth line in file2 not in file1
Fifth line in file2 not in file1
Sixth line in file2 not in file1

编辑添加了新方法

下面的批处理文件不需要文件中的任何顺序。但是,文件不能包含等号字符并且感叹号会被去除。此过程不区分大小写,因此将不同大小写的相同字符的两行视为相等。

@echo off
setlocal EnableDelayedExpansion

rem Read lines from file2
set i=100000
for /F "delims=" %%a in (file2.txt) do (
   set /A i+=1
   set "line[%%a]=!i:~-5!"
)

rem Remove lines from file1
for /F "delims=" %%a in (file1.txt) do (
   set "line[%%a]="
)

echo Result in sorted order:
for /F "tokens=2 delims=[]" %%a in ('set line[') do echo %%a

echo/
echo Result in original file2 order:
(for /F "tokens=2* delims=[]=" %%a in ('set line[') do echo %%bÿ%%a) > temp.txt
for /F "tokens=2 delims=ÿ" %%a in ('sort temp.txt') do echo %%a
del temp.txt
于 2013-11-15T18:46:17.217 回答