Ricardo Alves
Ricardo Alves

Reputation: 1131

Windows batch file: For loop each file obtained via DIR command

I have the following bat file:

@ECHO OFF
SET @logPath=C:\Users\rialves\Documents\Teste\
SET @date=2015-04-07
@ECHO ON
FOR /f %%f IN ('DIR /s /b %@logPath% ^| findstr %@date% ^| findstr .zip') DO ECHO %%f
PAUSE

If I run the command DIR /s /b %@logPath% | findstr %@date% | findstr .zip
I get the following output:

C:\Users\rialves\Documents\Teste\REST.API\rest api 1\2015-04-07.zip
C:\Users\rialves\Documents\Teste\REST.API\rest api 1\teste 2015-04-07 - Copy.zip
C:\Users\rialves\Documents\Teste\REST.API\rest api 1 - Copy\2015-04-07.zip
C:\Users\rialves\Documents\Teste\REST.API\rest api 1 - Copy (2)\2015-04-07.zip
C:\Users\rialves\Documents\Teste\REST.API\rest api 1 - Copy (3)\2015-04-07.zip
C:\Users\rialves\Documents\Teste\REST.API\rest api 1 - Copy (4)\2015-04-07.zip
C:\Users\rialves\Documents\Teste\REST.API\rest api 1 - Copy (5)\2015-04-07.zip

However, when echoing via FOR loop I get:

C:\Users\rialves\Documents\Teste>ECHO C:\Users\rialves\Documents\Teste\REST.API\rest
C:\Users\rialves\Documents\Teste\REST.API\rest

C:\Users\rialves\Documents\Teste>ECHO C:\Users\rialves\Documents\Teste\REST.API\rest
C:\Users\rialves\Documents\Teste\REST.API\rest

C:\Users\rialves\Documents\Teste>ECHO C:\Users\rialves\Documents\Teste\REST.API\rest
C:\Users\rialves\Documents\Teste\REST.API\rest

C:\Users\rialves\Documents\Teste>ECHO C:\Users\rialves\Documents\Teste\REST.API\rest
C:\Users\rialves\Documents\Teste\REST.API\rest

C:\Users\rialves\Documents\Teste>ECHO C:\Users\rialves\Documents\Teste\REST.API\rest
C:\Users\rialves\Documents\Teste\REST.API\rest

C:\Users\rialves\Documents\Teste>ECHO C:\Users\rialves\Documents\Teste\REST.API\rest
C:\Users\rialves\Documents\Teste\REST.API\rest

C:\Users\rialves\Documents\Teste>ECHO C:\Users\rialves\Documents\Teste\REST.API\rest
C:\Users\rialves\Documents\Teste\REST.API\rest

Why is that and how can I fix it?

Upvotes: 0

Views: 85

Answers (1)

dbenham
dbenham

Reputation: 130919

Your output strings are truncated at the first space within the path because FOR /F defaults to parsing tokens delimited by spaces and/or tabs.

The solution is simple - disable the DELIMS option in your FOR /F so that the entire path is considered to be a single token.

FOR /f "delims=" %%f IN ...

Upvotes: 2

Related Questions