Page 1 of 1

FOR doesn't iterate properly

Posted: 05 Sep 2020 21:45
by TheDrake
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

Re: FOR doesn't iterate properly

Posted: 06 Sep 2020 05:10
by penpen
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

Re: FOR doesn't iterate properly

Posted: 06 Sep 2020 08:12
by Eureka!
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
)

Re: FOR doesn't iterate properly

Posted: 06 Sep 2020 11:25
by pieh-ejdsch
You can display the for variable so that it only expands to the filename.

Code: Select all

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

Re: FOR doesn't iterate properly

Posted: 06 Sep 2020 14:24
by TheDrake
@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.