Search code examples
for-loopbatch-filefile-handling

Is there a way to loop through a files contents and use it in batch?


I'm working on a project in batch-file and need to read the contents of a file and print out the contents. I have a set up a for /f loop to go through the contents of the file, but it isn't working.

The Code

cd C:\Users\(name)
for /f %%G in (List.txt) (
    del /F /S %%G
    echo %errorlevel%
    pause
)

I have been Googling for about an hour now, and can't find anything which has worked for me. I was hoping that you guys could tell me what I'm doing wrong with my code.


Solution

  • Default delimiters in cmd for the for /F loop is whitespace. Your code will split and assign the first word/number/line up until the first whitespace.

    You need to tell the for /f loop to not use any delimiters. Also usebackq in order for you to double quote your file as that can also be a full path to the file with whitespace, i.e: "C:\My Documents\Old Files\list.txt"

    @echo off
    for /f "usebackq delims=" %%i in ("List.txt") do del /F /S "%%~i"
    

    then, del does not set the errorlevel and you will always get 0 returned. if you really want to check the result, redirect stderr to stdout and use findstr to determine if delete was successful.