FOR command - skip first row in the file

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
kabalman
Posts: 3
Joined: 04 May 2010 10:38

FOR command - skip first row in the file

#1 Post by kabalman » 05 May 2010 10:28

Hi

I have a file temp.txt with a list of file names generated via a
dir /b /o:N file*.txt > temp.txt
command.

So temp.txt contains
file.txt
file1.txt
file2.txt

I now want to read the contents of temp.txt and skip the first row and delete the files whose filenames are denoted in the other 2 rows. To do this, I wrote a FOR command to read the file and process it.

set /a counter=0
FOR /f "tokens=* delims= " %%i in (temp.txt) do (
if %counter% EQU 1 (del %%i)
if %counter% EQU 0 (set /a counter+=1)
)

At the end of running the batch file, it is setting the counter to a value of 3 and not deleting any of the 3 files. It clearly proves that the "if" command is not working. Can you please tell me what is wrong with this or if there is a different way to do this.

Please note that the number of files in the directory is variable and I always want to delete all of them except the first one. Please advise.

aGerman
Expert
Posts: 4678
Joined: 22 Jan 2010 18:01
Location: Germany

Re: FOR command - skip first row in the file

#2 Post by aGerman » 05 May 2010 11:21

During the run time of a command line the value of a variable will be expanded only once. A multiline FOR loop is interpreted as only one command line. This means the value of %counter% is 0 inside your FOR loop and seems not to be changed... I could write even more, but it's a bit off topic.
To solve your problem: You've written the solution in your topic. skip

Code: Select all

for /f "skip=1 delims=" %%i in (temp.txt) do del "%%i"

No counter is needed :wink:

Once more I suggest to write
for /?
to the command prompt to get help.

Regards
aGerman

Post Reply