463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122458

How to get filename in variable inside loop?

I want to loop through all .h files in the current directory and call a batch function for the corresponding .cpp file. Actually I had it working already, but when I tried to use local variables I get some strange output.

SETLOCAL

for /R  %%f in (*.h) do (
    SET header=%f%
    ECHO header=%header%
    SET source=%%~df%%~pf%%~nf.cpp
    ECHO source=%source%
)

I get this output:

SETLOCAL

C:\WorkingDirectory>(
SET header=
 ECHO header=
 SET source=C:\WorkingDirectory\SomeFile.cpp
 ECHO source=
)
header=
source=

Why is %%~df%%~pf%%~nf.cpp correctly expanded, but ECHO %source% prints nothing? How can I correctly SET header=%f%?

Upvotes: 0

Views: 1043

Answers (1)

geisterfurz007
geisterfurz007

Reputation: 5874

1) The variable you are accessing is not accessed with %f% but %%f

2) As @npocmaka already mentioned as a comment DelayedExpansion is needed as in batch every block of closed parenthesis is parsed at once when using the usual %. To get rid of that problem, add setlocal EnableDelayedExpansion to your script after @echo off and change %header% to !header!. The same goes for %source%, but not so for the loop variable %%f!

SETLOCAL EnableDelayedExpansion

for  %%f in (*.h) do (
    SET header=%%~ff
    ECHO header=!header!
    SET source=%%~df%%~pf%%~nf.cpp
    ECHO source=!source!
)

Upvotes: 1

Related Questions