How can I test if a list of files exist?

后端 未结 6 2139
花落未央
花落未央 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: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
    

提交回复
热议问题