How can I test if a list of files exist?

后端 未结 6 2140
花落未央
花落未央 2021-02-15 18:25

I have a file that lists filenames, each on it\'s own line, and I want to test if each exists in a particular directory. For example, some sample lines of the file might be

相关标签:
6条回答
  • 2021-02-15 19:13

    I wanted to add one small comment to most of the above solutions. They are not actually testing if a particular file exists or not. They are checking to see if the file exists and you have access to it. It's entirely possible for a file to exist in a directory you do not have permission to in which case you won't be able to view the file even though it exists.

    0 讨论(0)
  • 2021-02-15 19:17

    Please note, however, that using the default file systems under both Win32 and *nix there is no way to guarantee the atomicity of the operation, i.e. if you check for the existence of files A, B, and C, some other process or thread might have deleted file A after you passed it and while you were looking for B and C.

    File systems such as Transactional NTFS can overcome this limitation.

    0 讨论(0)
  • 2021-02-15 19:21

    In cmd.exe, the FOR /F %variable IN ( filename ) DO command should give you what you want. This reads the contents of filename (and they could be more than one filenames) one line at a time, placing the line in %variable (more or less; do a HELP FOR in a command prompt). If no one else supplies a command script, I will attempt.

    EDIT: my attempt for a cmd.exe script that does the requested:

    @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 must be a script; a FOR loop in a .cmd or .bat file, for some strange reason, must have double percent-signs before 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
    
    0 讨论(0)
  • 2021-02-15 19:22
    for /f %i in (files.txt) do @if exist "%i" (@echo Present: %i) else (@echo Missing: %i)
    
    0 讨论(0)
  • 2021-02-15 19:22

    Bash:

    while read f; do 
        [ -f "$f" ] && echo "$f" exists
    done < file.txt
    
    0 讨论(0)
  • 2021-02-15 19:27

    In 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 it; it is a way I know of; 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
    
    0 讨论(0)
提交回复
热议问题