【问题标题】:if exist check with case sensitive in batch如果存在批量检查区分大小写
【发布时间】:2013-06-20 19:05:42
【问题描述】:

我需要检查给定文件是否存在,区分大小写,out.txt(都是小写字母)文件存在于我运行脚本的位置。

代码:

Case1:
filename=out.txt
 if exist %filename% (
    echo file exist...
) else echo File doesn't exist...

Case2:
filename=OUT.TXT
if exist %filename% (
    echo file exist...
) else echo File doesn't exist...

对于这两种情况,它都显示文件存在...输出。但我需要检查是否区分大小写。它应该为 OUT.TXT 显示“文件不存在”消息

提前致谢

【问题讨论】:

    标签: windows batch-file


    【解决方案1】:

    从参数中获取文件名:

    @echo off 
    dir /b /a-d "%~1"|find "%~1" >nul
    if %errorlevel% == 0 (echo found) else (echo fail)
    

    dir实际上不区分大小写 - 但find 是...

    【讨论】:

    • 使用更安全dir /b /a-d "%~1"|find "%~1" >nul
    • 一行两个改进——不错!
    • dir /B /A:-D "%~1" | findstr /X /C:"%~1" > nul 呢?
    • @aschipfl 不需要/X,因为dir已经过滤了文件。也不需要findstr /C,因为find 已经处理带有空格的字符串。但将实施其他建议(dbenham 已经提出)
    【解决方案2】:

    新增文件列表解析:

    @echo off
    for /f "delims=" %%z in ('type "namelist.txt" ') do (
    if not exist "%%~z" echo "%%~z" not found
    if     exist "%%~z" for %%a in ("%%~z") do if "%%a"=="%%~z" (echo "%%~z" is the right case) else (echo "%%~z" is the wrong case "%%a found")
    )
    pause
    

    【讨论】:

    • 谢谢...但是这里的脚本从另一个脚本获取文件名作为输入..我们不知道这里的文件名可以像“OUT.TXT”那样进行比较。如果我们比较类似,for %%a in (%filename%) do if "%%a"=="%filename%" echo file exists... 结果与 "if exists %filename%" 相同
    • @user15536​​05 如果你想解析文件名列表,那么就这么说吧。我的代码按照你的要求做了。有关文件解析,请参见上面的更改。
    猜你喜欢
    • 1970-01-01
    • 2015-06-04
    • 2021-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-17
    • 2010-11-27
    • 2016-12-25
    相关资源
    最近更新 更多