How to check if a file list exists?

I have a file listing file names, each of which is on its own line, and I want to check if they exist in a specific directory. For example, some sample file lines may be

mshta.dll foobar.dll somethingelse.dll 

I'm interested in the X:\Windows\System32\ directory, so I want to see if the following files exist:

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

How to do this using the Windows command line? Also (out of curiosity), how would I do this using bash or another Unix shell?

+7
command-line file shell
source share
6 answers

In cmd.exe, the FOR / F% command of the IN variable ( file_name ) DO should provide you with what you want. This reads the contents of the file name (and there may be several file names) one line at a time, placing the line in the% variable (more or less, do HELP FOR on the command line). If no one else executes the script command, I will try to execute.

EDIT: my attempt for a cmd.exe script that asks:

 @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 

Note. The script above should be a script; The FOR loop in a .cmd or .bat file, for some strange reason, should have a double percentage sign in front of its variable.

Now, for a script that works with 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 
+9
source share

Bash:

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

On Windows:

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

(This may not be the best way to do this, I know, see also http://blogs.msdn.com/oldnewthing/archive/2008/09/26/8965755.aspx

In Bash:

 if ( test -e file.txt ); then echo "file exists"; fi 
+1
source share

Please note, however, that using the default file systems under Win32 and * nix does not guarantee the atomicity of the operation, i.e. if you check for the presence of files A, B, and C, some other process or thread may have deleted file A after it was transferred, and while you were looking for B and C.

File systems such as Transactional NTFS can overcome this limitation.

+1
source share

I wanted to add one small comment to most of the above solutions. They actually do not check if any particular file exists or not. They check if the file exists and you have access to it. Perhaps the file exists in a directory in which you do not have permission, in which case you will not be able to view the file, even if it exists.

+1
source share

All Articles