如何测试文件列表是否存在?

Jus*_*oss 7 shell command-line file

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

mshta.dll
foobar.dll
somethingelse.dll
Run Code Online (Sandbox Code Playgroud)

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

X:\Windows\System32\mshta.dll
X:\Windows\System32\foobar.dll
X:\Windows\System32\somethingelse.dll
Run Code Online (Sandbox Code Playgroud)

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

Jes*_*erE 9

击:

while read f; do 
    [ -f "$f" ] && echo "$f" exists
done < file.txt
Run Code Online (Sandbox Code Playgroud)


tzo*_*zot 9

在cmd.exe中,FOR/F%变量 IN( 文件名 )DO 命令应该为您提供所需的内容.此读取的内容文件名(和它们可以是多于一个的文件名)在每次一行,放置在%变量行(或多或少;做有助于为在命令提示).如果没有其他人提供命令脚本,我会尝试.

编辑:我尝试执行所请求的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
Run Code Online (Sandbox Code Playgroud)

注意,上面的脚本必须是脚本; .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
Run Code Online (Sandbox Code Playgroud)