首页 > 解决方案 > 用于在同一字典中查找重复文件名的批处理脚本

问题描述

我需要在同一个目录中找到同名的文件并打印它们的名称并返回一些错误代码。此时它工作正常,但文件名被打印了几次。我以一种相当原始的方式做到了。

fo2 包含文件:

Abc123
BBBB
CCCC
CCCCaaa
CCCCbbb
CCCCrrr

我的输出:

CCCCaaa
CCCCbbb
CCCCrrr
CCCC
CCCCbbb
CCCCrrr
CCCC
CCCCaaa
CCCCrrr
CCCC
CCCCaaa
CCCCbbb

预期结果:

CCCCaaa
CCCCbbb
CCCCrrr
CCCC

我的代码:

@ECHO Off
SetLocal EnableDelayedExpansion

    for /R C:\Users\operator\Desktop\batch\fol2 %%a in (*.*) do (

        set fileDic1=%%~nxa
        set fileConcatPart1Dic1=!fileDic1:~0,3%!
        set fileConcatPart2Dic1=!fileDic1:~3%!
    
        for /R C:\Users\operator\Desktop\batch\fol2 %%b in (*.*) do (
    
            set fileDic2=%%~nxb
            set fileConcatPart1Dic2=!fileDic2:~0,3%!
            set fileConcatPart2Dic2=!fileDic2:~3%!
            REM echo !fileConcatPart1Dic1!
            REM echo !fileDic2!
            if !fileConcatPart1Dic1!==!fileConcatPart1Dic2! (if not !fileConcatPart2Dic1!==!fileConcatPart2Dic2! (echo %%~nxb)) 
        
        )

    )

我知道已经出现了类似的主题,但我想评估我的代码并获得有关如何以不同、更好、也许更简单的方式来完成它的建议。

标签: windowsbatch-filecmdduplicates

解决方案


@ECHO Off
SetLocal EnableDelayedExpansion

:: remove variables starting #
FOR  /F "delims==" %%a In ('set # 2^>Nul') DO SET "%%a="


    for /R C:\Users\operator\Desktop\batch\fol2 %%a in (*.*) do (

        set fileDic1=%%~nxa
        set fileConcatPart1Dic1=!fileDic1:~0,3%!
        set fileConcatPart2Dic1=!fileDic1:~3%!
    
        for /R C:\Users\operator\Desktop\batch\fol2 %%b in (*.*) do (
    
            set fileDic2=%%~nxb
            set fileConcatPart1Dic2=!fileDic2:~0,3%!
            set fileConcatPart2Dic2=!fileDic2:~3%!
            REM echo !fileConcatPart1Dic1!
            REM echo !fileDic2!
            if !fileConcatPart1Dic1!==!fileConcatPart1Dic2! if not !fileConcatPart2Dic1!==!fileConcatPart2Dic2! if not defined #%%~nxb (
               echo %%~nxb
               set "#%%~nxb=Y"
            ) 
        
        )

    )

应该适合你。

更改是:which 应该从环境中删除任何以开头的变量
(不太可能是任何变量,但这可以确保) 删除了条件周围的括号-如果您不使用子句,您可以级联语句。 添加了第三个来检测变量是否已被设置。如果未设置,则将在编辑名称时设置。由于它随后被设置(设置为非空值),它将无法通过测试,因此不会重复该名称。for /f...set # ...#
if not...ifelse
if#%%~nxbechonot defined


推荐阅读