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

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?

有帮助吗?

解决方案

在cmd.exe中, FOR / F% 变量 IN( 文件名 )DO 命令可以为您提供所需内容。这一行一行读取 filename 的内容(它们可能是多个文件名),将行放在%变量中(或多或少;在命令提示符下执行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

其他提示

击:

while read f; do 
    [ -f "$f" ] && echo "$f" exists
done < file.txt
for /f %i in (files.txt) do @if exist "%i" (@echo Present: %i) else (@echo Missing: %i)

在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

但请注意,使用Win32和* nix下的默认文件系统无法保证操作的原子性,即如果检查文件A,B和C是否存在,还有其他一些在您传递文件A并且在查找B和C时,进程或线程可能已删除了文件A.

Transactional NTFS 等文件系统可以克服这个问题限制。

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top