文件 1
A
B
C
文件 2
B
C
D
文件 1 + 文件 2 =
A
B
C
D
是否可以使用cmd.exe?
如果您可以使用不区分大小写的比较,并且您知道所有行都不超过 511 字节(XP 为 127),那么您可以使用以下命令:
@echo off
copy file1.txt merge.txt >nul
findstr /lvxig:file1.txt file2.txt >>merge.txt
type merge.txt
有关限制的说明,请参阅Windows FINDSTR 命令有哪些未记录的功能和限制?.
使用 PowerShell:
Get-Content file?.txt | Sort-Object | Get-Unique > result.txt
对于cmd.exe
:
@echo off
type nul > temp.txt
type nul > result.txt,
copy file1.txt+file2.txt temp.txt
for /f "delims=" %%I in (temp.txt) do findstr /X /C:"%%I" result.txt >NUL ||(echo;%%I)>>result.txt
del temp.txt
第一部分(合并两个文本文件)是可能的。(见命令文档copy
)
copy file1.txt+file2.txt file1and2.txt
对于第 2 部分,您可以使用CoreUtils for Windowssort
中的uniq
实用程序。这是 linux 实用程序的 windows 端口。
sort file1and2.txt filesorted.txt
uniq filesorted.txt fileunique.txt
这有一个限制,您将失去对原始排序的跟踪。
更新 1
Windows 还附带本机SORT.EXE。
更新 2
您也可以使用与纯 Batch 相同的 Unix 或 PowerShell 方法,开发一个简单的uniq.bat
过滤程序:
@echo off
setlocal EnableDelayedExpansion
set "prevLine="
for /F "delims=" %%a in ('findstr "^"') do (
if "%%a" neq "!prevLine!" (
echo %%a
set "prevLine=%%a"
)
)
编辑:下面的程序是程序的 Batch-JScript 混合版本uniq
,更可靠,更快;将此程序复制到一个名为的文件中uniq.bat
:
@if (@CodeSection == @Batch) @then
@CScript //nologo //E:JScript "%~F0" & goto :EOF
@end
var line, prevLine = "";
while ( ! WScript.Stdin.AtEndOfStream ) {
line = WScript.Stdin.ReadLine();
if ( line != prevLine ) {
WScript.Stdout.WriteLine(line);
prevLine = line;
}
}
这样,您可以使用此解决方案:
(type file1.txt & type file2.txt) | sort | uniq > result.txt
但是,在这种情况下,结果丢失了原始顺序。
下面的解决方案假设两个输入文件都使用相同的IF
命令比较运算符顺序按升序排序,并且不包含空行。
@echo off
setlocal EnableDelayedExpansion
set "lastLine=ÿ"
for /L %%i in (1,1,10) do set "lastLine=!lastLine!!lastLine!"
< file1.txt (
for /F "delims=" %%a in (file2.txt) do (
set "line2=%%a"
if not defined line1 set /P line1=
if "!line1!" lss "!line2!" call :advanceLine1
if "!line1!" equ "!line2!" (
echo !line1!
set "line1="
) else (
echo !line2!
)
)
)
if "!line1!" neq "%lastLine%" echo !line1!
goto :EOF
:advanceLine1
echo !line1!
set "line1="
set /P line1=
if not defined line1 set "line1=%lastLine%"
if "!line1!" lss "!line2!" goto advanceLine1
exit /B