Batch file to check if the file list exists. Doesn't work with spaces
I have a list of files in a text file and I would like to generate a report of any files that do not exist. I tried to create a batch file with the following code, however, it does not work with files that have a space in this path:
FOR /F %%f IN (filelist.txt) DO (IF EXIST %%f (ECHO %%f exists) ELSE (ECHO %%f doesn't exist >> C:\doesntexist.txt ))
My output file shows an error like "C: \ Documents does not exist" showing that it did not parse the full filename.
How can I fix this so that I can check all files even with spaces in the path?
source to share
If there is a possibility that the string might contain a delimiter such as a space, you need "enclose that string in quotes"
for /f
tokenises the data it receives by default in delimiters, so the first nominated token is assigned to a meta variable ( %%f
in your case), next to %%g
and so on.
You can control the number of tokens and delimiters and other parsing characteristics with command modifiers (see from the prompt for /?
)
In your case, you only need one token with no delimiters (default is 1 token and delimiters = delimiters), so
FOR /F "delims=" %%f IN (filelist.txt) DO (IF EXIST "%%f" (ECHO %%f exists) ELSE (ECHO %%f doesn't exist >> C:\doesntexist.txt ))
There is a slight additional complication if it filelist.txt
contains spaces. In this case, you will need
FOR /F "usebackqdelims=" %%f IN ("filelist.txt") DO (IF EXIST "%%f" (ECHO %%f exists) ELSE (ECHO %%f doesn't exist >> C:\doesntexist.txt ))
for the reasons that are "explained" in the documentation for /?
mentioned above.
source to share