【问题标题】:Batch file to compare contents of a text file用于比较文本文件内容的批处理文件
【发布时间】:2012-07-12 22:06:01
【问题描述】:

我有两个包含以下数字的文本文件

File1
00000
11111

File2
00000
11111
22222

我需要一个代码,将 file2 的内容与 file1 的内容以及不匹配的数字进行比较,在这种情况下,'22222' 是 file2 中唯一的内容。

简而言之,我想擦除 file2 的内容并将不匹配的内容放入 file2。下面是我尝试过的代码,但它只是删除了 file2 中的整个内容。

setlocal enabledelayedexpansion

for /f "tokens=1" %%a in (file1) do (type file2 | findstr /v %%a > file2)

pause

底线我需要达到以下结果

File1
00000
11111

File2
22222

请帮忙!

【问题讨论】:

    标签: file batch-file compare


    【解决方案1】:

    我认为这是最简单最快的原生批处理解决方案

    findstr /vixg:"File1" "File2" >"File2.new"
    move /y "File2.new" "File2"
    

    请注意,我使用了findstr /i 不区分大小写选项。这一点很重要,因为 findstr bug 在搜索多个文字字符串时可能导致丢失匹配,除非使用 /i/r 选项。由于您正在处理数字,因此不区分大小写的解决方法不应影响您。

    【讨论】:

      【解决方案2】:

      这可以完成工作。它取决于使用 findstr /m 选项和错误级别。

      它还在处理过程中写入临时文件(并清理它)。

      
      @echo off
      setlocal enabledelayedexpansion
      echo Stripping duplicates in file2 (%2) compared to lines in file1 (%1)
      
      if not exist "%1" (
        echo That first file doesn't exist.
        exit /b 1
      )
      
      if not exist "%2" (
        echo That second file doesn't exist.
        exit /b 2
      )
      
      REM Create empty temporary file
      echo. 2> %2.tmp
      
      for /f "tokens=1" %%a in (%2) do (
        echo Processing %%a
        >nul call findstr /m "%%a" %1
        if errorlevel 1 (
          echo OK
          >> %2.tmp echo %%a
        ) else (
          echo Duplicate!
        )
      )
      
      
      echo Writing results to %2
      xcopy /y /q %2.tmp %2
      del /q %2.tmp
      

      【讨论】:

        【解决方案3】:

        不同的做法:

        @echo off
        setlocal 
        for /f %%i in (file1) do set %%i=%%i
        for /f %%j in (file2) do if not defined %%j echo %%j 
        

        它具有以下特点:
        - 仅扫描每个文件一次
        - file1 中的重复项将被有效忽略
        - 您可以将 file1 加载到内存中,然后针对它运行几个 file_x 进行测试。

        注意事项:
        我只是将唯一的数字回显到控制台,您需要更改为写入文件
        假设您比较 单词 并且每行一个单词
        它受限于可以定义的最大变量数。我不知道那个数字是什么...我在 file1 中尝试了 20 000 行(因此定义了 20 000 个变量)

        【讨论】:

          【解决方案4】:

          这可能是解决方案之一:

          findstr /V /G:file1.txt file2.txt
          

          【讨论】:

          • 这个答案与 4 年前的答案相比没有引入任何新内容,除了错误 - 1) 缺少 /I 选项会暴露 FINDSTR 处理多个搜索词的错误,2) 缺少 /X 选项允许 2 匹配 123,3) 不解决用结果覆盖 file2.txt 的问题。
          猜你喜欢
          • 1970-01-01
          • 2015-05-09
          • 2014-12-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-06-15
          • 1970-01-01
          相关资源
          最近更新 更多