在批处理脚本中查找未知的文本文件

时间:2014-02-24 09:15:43

标签: batch-file

我正在编写一个批处理脚本,用于检查目录中是否存在文本文件。我使用以下命令

if exist "test\dir\*.txt" 
(
    echo txt file exist
)

好像命令在搜索时没有区分大写和小写,所以我打算使用find命令,但我无法将其与*.txt一起使用。

有人可以告诉我如何使用find命令搜索未知的文本文件?

2 个答案:

答案 0 :(得分:1)

要测试文件是否存在,您可以使用以下任何一种

if exist "test\dir\*.txt" (
    echo File exists
) else (
    echo File does not exist
)


if exist "test\dir\*.txt" echo File exists


dir /a-d "test\dir\*.txt" > nul 2>nul
if errorlevel 1 (
    echo File does not exist
) else echo File exists


dir /a-d "test\dir\*.txt" >nul 2>nul && echo File Exists || echo File does not exist

只是列举习惯性的方式。

但是,正如你所说,所有这些结构都不区分大小写。

find用于查找文件内的文本,而不是文件搜索。但是,如果搜索必须区分大小写,则必须将先前样本中对文件存在的简单检查转换为文件的枚举,然后在列表中搜索所需文件。

dir /a-d /b "test\dir\*.txt" 2>nul | find ".txt" > nul
if errorlevel 1 (
    echo File does not exist
) else echo File exists

但是这将返回myfile.txt.exe存在的文件。对于这样的事情,findstr更灵活,允许指示搜索字符串的位置。在这种情况下,在行的末尾

dir /a-d /b "test\dir\*.txt" 2>nul | findstr /l /e /c:".txt" > nul
if errorlevel 1 (
    echo File does not exist
) else echo File exists

此枚举与*.txt匹配的文件,并以小写字母筛选列表(/l切换).txt/c:参数)的列表(默认行为),在行的末尾(/e开关)

答案 1 :(得分:0)

dir / s将在给定目录及其子目录中搜索文件模式。执行后检查ERRORLEVEL将允许知道文件是否被找到。

相关问题