Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch File to check if list of files exist. 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 creating a batch file with the following code however it does not work with any files that have a space in it's path:

FOR /F %%f IN (filelist.txt) DO (IF EXIST %%f (ECHO %%f exists) ELSE (ECHO %%f doesn't exist >> C:\doesntexist.txt ))

In my output file I get an error like "C:\Documents doesn't exist" showing that it didnt parse the full file name.

How can I fix this so that I can check all files even with spaces in it's path?

like image 280
Chauncy Peppertooth Avatar asked Dec 29 '25 08:12

Chauncy Peppertooth


1 Answers

Wherever there is a possibility that a string may contain a separator like a space, you need to "enclose that string in quotes"

for /f tokenises the data it receives by default on separators, so the first nominated token is assigned to the metavariable (%%f in your case), the next to %%g and so on.

You can control how many tokens and the delimiter(s) and other parsing characteristics by using command-modifiers (from the prompt, see for /?)

In your case, you want just the one token with no delimiters (the default is 1 token and delimiters=separators) 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 small extra complication if filelist.txt contains spaces. In that case, you'd 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 reasons that ate "explained" in the documentation for /? referred to above.

like image 146
Magoo Avatar answered Jan 01 '26 19:01

Magoo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!