如何测试文件列表是否存在?
我有一个列出文件名的文件,每个文件名都在自己的行上,我想测试每个文件名是否存在于特定目录中。例如,文件的某些示例行可能是
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进行此操作?
解决方案
在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
重击:
while read f; do [ -f "$f" ] && echo "$f" exists done < file.txt
但是请注意,使用Win32和* nix下的默认文件系统无法保证操作的原子性,即如果检查文件A,B和C,其他进程或者线程是否存在传递文件之后以及正在寻找文件B和文件C时,它们可能已经删除了文件A。
诸如Transactional NTFS之类的文件系统可以克服此限制。
在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
我想对上述大多数解决方案添加一个小意见。他们实际上并没有测试是否存在特定文件。他们正在检查文件是否存在,我们是否有权访问它。文件完全可能存在于我们没有权限的目录中,在这种情况下,即使该文件存在,我们也将无法查看。
for /f %i in (files.txt) do @if exist "%i" (@echo Present: %i) else (@echo Missing: %i)