8

我有一个列出文件名的文件,每个文件名都在它自己的行上,我想测试每个文件名是否存在于特定目录中。例如,文件的一些示例行可能是

mshta.dll
foobar.dll
somethingelse.dll

我感兴趣的目录是X:\Windows\System32\,所以想看看是否存在以下文件:

X:\Windows\System32\mshta.dll
X:\Windows\System32\foobar.dll
X:\Windows\System32\somethingelse.dll

如何使用 Windows 命令提示符执行此操作?另外(出于好奇)我将如何使用 bash 或其他 Unix shell 来做到这一点?

4

6 回答 6

10

重击:

while read f; do 
    [ -f "$f" ] && echo "$f" exists
done < file.txt
于 2008-09-29T21:37:13.377 回答
10

在 cmd.exe 中,FOR /F % variable IN ( filename ) DO 命令应该可以满足您的需求。这会一次读取一行文件名的内容它们可能是多个文件名),将该行放在 %variable 中(或多或少;在命令提示符下执行 HELP FOR)。如果没有其他人提供命令脚本,我会尝试。

编辑:我尝试执行请求的 cmd.exe 脚本:

@echo off
rem first arg is the file containing filenames
rem second arg is the target directory

FOR /F %%f IN (%1) DO IF EXIST %2\%%f ECHO %%f exists in %2

注意,上面的脚本必须是脚本;出于某种奇怪的原因,.cmd 或 .bat 文件中的 FOR 循环必须在其变量之前有两个百分号。

现在,对于与 bash|ash|dash|sh|ksh 一起使用的脚本:

filename="${1:-please specify filename containing filenames}"
directory="${2:-please specify directory to check}
for fn in `cat "$filename"`
do
    [ -f "$directory"/"$fn" ] && echo "$fn" exists in "$directory"
done
于 2008-09-29T21:38:32.597 回答
2
for /f %i in (files.txt) do @if exist "%i" (@echo Present: %i) else (@echo Missing: %i)
于 2008-09-30T17:26:23.097 回答
1

在 Windows 中:


type file.txt >NUL 2>NUL
if ERRORLEVEL 1 then echo "file doesn't exist"

(这可能不是最好的方法;这是我知道的一种方法;另见http://blogs.msdn.com/oldnewthing/archive/2008/09/26/8965755.aspx

在 Bash 中:


if ( test -e file.txt ); then echo "file exists"; fi
于 2008-09-29T21:34:25.287 回答
1

但是请注意,在 Win32 和 *nix 下使用默认文件系统无法保证操作的原子性,即如果您检查文件 A、B 和 C 是否存在,则其他进程或线程可能在您通过文件 A 之后以及在您寻找 B 和 C 时删除了它。

Transactional NTFS等文件系统可以克服这一限制。

于 2008-09-29T21:38:22.657 回答
1

我想对上述大多数解决方案添加一个小评论。他们实际上并没有测试特定文件是否存在。他们正在检查文件是否存在并且您可以访问它。文件完全有可能存在于您无权访问的目录中,在这种情况下,即使该文件存在,您也无法查看该文件。

于 2008-09-29T22:45:41.873 回答