【问题标题】:Batch File Using DIFF and FINDSTR to Compare and Output Differences Between 2 Files批处理文件使用 DIFF 和 FINDSTR 比较和输出 2 个文件之间的差异
【发布时间】:2014-06-03 12:53:43
【问题描述】:

我正在尝试比较两个文件(old.txt 和 new.txt),如果 new.txt 中的任何行与 old.txt 不同,则输出到 txt 文件。我不希望新文件中出现 old.txt 中的任何行。

新文件上传到 c:\temp\download 并在处理后复制到 c:\temp\download\archived。

我在下面使用的脚本将在 c:\temp\download 中找到最新文件,并将其与 c:\temp\download\archived 中的最后修改文件进行比较,并将差异输出到 txt 文件。它在大多数情况下都有效,但我面临的问题是输出 (%latestD%) 文件还包含 old.txt 中的行。它应该是单向比较,新旧对比,输出应该包含 old.txt 中的行。

这是我想要实现的目标:

OLD.txt
吉姆 789
简 123
詹姆斯 999
百合 111

NEW.txt
吉姆 123
简 123
詹姆斯 123

OUTPUT.txt
吉姆 123
詹姆斯 123

set "fC=C:\temp\download"
set "latestC="
for /f "delims=" %%a in ('dir "%fC%" /b /od /a-d /tw 2^>nul') do set "latest=%%a" & set   "latestC=%fC%\%%a"
set "fD=C:\temp\download\archived
set "latestD="
for /f "delims=" %%a in ('dir "%fD%" /b /od /a-d /tw 2^>nul') do set "latestD=%fD%\%%a"
if not defined latestC ( echo NO File in C & exit /b )
if not defined latestD ( echo NO File in D & exit /b )
for /f "tokens=1,*" %%a in (
'diff "%latestC%" "%latestD%" ^| findstr /r /c:"^<" /c:"^>"'
) do (
>> "C:\temp\%latest%" echo(%%b
)

谢谢!

【问题讨论】:

  • 文件是 html 吗?您的 findstr 命令正在输出 &lt;&gt; 并且批处理有限制。 FWIW Windows 没有diff 命令。
  • 文件都是*.txt文件。我已经安装了 cygwin,所以使用 unix diff 命令。
  • diff 命令在单独运行时是否提供您想要的内容,只需要文件名?
  • 如果我单独运行 diff 命令,我会得到相同的结果,输出的内容包含重复的行(一个来自 old.txt 和修改后的行来自 new.txt)。 old.txt 中存在而不是 new.txt 中的行也出现在输出中,而它们不应该出现在输出中。

标签: batch-file diff findstr


【解决方案1】:

这应该满足你的要求:

findstr /v /g:"old.txt" "new.txt"

【讨论】:

  • 要是这么简单就好了。 /L 选项需要强制字面解释。搜索字符串中的反斜杠 \ 可能需要转义为 \\,具体取决于上下文。最好总是逃避他们。杀手探针是一个讨厌的 FINDSTR 错误 - 多个不同长度的文字搜索字符串可能无法找到所有匹配项,除非使用 /I(不区分大小写)选项。见What are the undocumented features and limitations of the Windows FINDSTR command?
  • 谢谢戴夫。对于问题中引用的案例,它可以完美运行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-03
  • 1970-01-01
  • 2018-01-09
  • 1970-01-01
  • 2021-01-01
  • 1970-01-01
相关资源
最近更新 更多