FOR doesn't iterate properly

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
TheDrake
Posts: 2
Joined: 05 Sep 2020 21:35

FOR doesn't iterate properly

#1 Post by TheDrake » 05 Sep 2020 21:45

Hi folks. I have a simple script which is in a directory that contains the files DPI360.pdf, DPI361.pdf and DPI362.pdf:

Code: Select all

FOR %G IN (*.pdf) DO (
    SET newfile=%G
    SET dpi=%newfile:~0,6%
    echo %dpi%
)
I don't understand why it outputs thusly (pasted into Windows XP's CMD):
C:\printer>FOR %G IN (*.pdf) DO (
More? SET newfile=%G
More? SET dpi=%newfile:~0,6%
More? echo %dpi%
More? )

C:\printer>(
SET newfile=DPI360.pdf
SET dpi=DPI362
echo DPI362
)
DPI362

C:\printer>(
SET newfile=DPI361.pdf
SET dpi=DPI362
echo DPI362
)
DPI362

C:\printer>(
SET newfile=DPI362.pdf
SET dpi=DPI362
echo DPI362
)
DPI362
I expect
DPI360
DPI361
DPI362

penpen
Expert
Posts: 2009
Joined: 23 Jun 2013 06:15
Location: Germany

Re: FOR doesn't iterate properly

#2 Post by penpen » 06 Sep 2020 05:10

Typically the command line is echoingyou can avoid that by zsing a '@'-character at the right place, which should be something like the following:

Code: Select all

FOR %G IN (*.pdf) DO @(
    SET newfile=%G
    SET dpi=%newfile:~0,6%
    echo %dpi%
)

penpen

Eureka!
Posts: 137
Joined: 25 Jul 2019 18:25

Re: FOR doesn't iterate properly

#3 Post by Eureka! » 06 Sep 2020 08:12

Take a look at the explanation of delayed environment variable expansion (command: SET /?)

CMD reads FOR ... ( ...) as a single line and all variables will be expanded all at once when reading that entire line.
Example: This will only echo the same time multiple times (= the time when the command was read for the first time).

Code: Select all

@FOR %G IN (*.pdf) DO @(
    @echo %time%
    @timeout /t 1 > nul
)
Unless .. you use delayed environment variable expansion.

In batch-files you can use setlocal enabledelayedexpansion. On the command-line, you have to start a new CMD with delayed environment variable expansion enabled: CMD.exe /v
Then you can do this:

Code: Select all

@FOR %G IN (*.pdf) DO @(
    @echo !time!
    @timeout /t 1 > nul
)

pieh-ejdsch
Posts: 240
Joined: 04 Mar 2014 11:14
Location: germany

Re: FOR doesn't iterate properly

#4 Post by pieh-ejdsch » 06 Sep 2020 11:25

You can display the for variable so that it only expands to the filename.

Code: Select all

for %%G IN (*.pdf) DO Echo %%~nG

TheDrake
Posts: 2
Joined: 05 Sep 2020 21:35

Re: FOR doesn't iterate properly

#5 Post by TheDrake » 06 Sep 2020 14:24

@penpen, thank you, but I am aware of the echo feature; I meant that I never saw "DPI360" outputted on its own line.

@Eureka!, thank you; I was unaware of this part of DOS scripting!

@pieh-ejdsch, thank you, but it was the fact that I couldn't get "DPI360" to output that was the main issue.

Post Reply