Peter329
Peter329

Reputation: 11

Using variables in a for loop

I understand the magic of the setlocal enabledelayedexpansion; this brought me one step further but I am still not completely happy. I am now able to assign the filename to a !loop variable!, but I fail to use that variable subseqently. I try to get the filename without the extension. There must be something else that I am unaware of.

This is my coding now:

::process all files in directory
setlocal enabledelayedexpansion

for %%f in (C:\windows\*.ico) do (

    echo F=%%f
    set myname=%%f
    echo.N=!myname!
    call :strlen myLen "!myname!"
    echo.myLen=!myLen!

    set /A L=myLen-3 + 1
    set str=!myname!
    echo.str1=!str! L=!L!
    set str=!str:~0,!L! !    <-Remove extension from filename
    echo.str2=!str!          <-This does not work!

)

Here is the output of my call :

 F=C:\windows\AnyWeb Print.ico
 N=C:\windows\AnyWeb Print.ico
 Strlen C:\windows\AnyWeb Print.ico
 myLen=25
 str1=C:\windows\AnyWeb Print.ico L=23
 str2=L       <--- what went wrong ????

Upvotes: 0

Views: 70

Answers (2)

Magoo
Magoo

Reputation: 79982

In the general case,

CALL set str=%%str:~0,!L!%%

This executes a subshell where the command set str=%str:~0,{the value of L}% is executed.

But please note that not all filenames have a 3-character extension; the for modifiers are a better bet for that application. This method is a general-purpose get the first L characters of a string where L's instantaneous value is required.

Upvotes: 0

jeb
jeb

Reputation: 82202

The problem is the line

set str=!str:~0,!L! !    <-Remove extension from filename

The exclamation marks are used from left to right, you get two parts

set str=!str:~0,! and L! !

This could be solved by using a different form of expansion, like FOR-loop-parameter, like

for %%X in (!L!) DO set str=!str:~0,%%X!

But in your case there exist a much simpler solution

for %%C in (C:\windows\*.ico) do (

  set myname=%%C
  set name_without_extension=%%~nC
  echo Name=!myname!
  echo Only Name=!name_without_extension!
)

Upvotes: 1

Related Questions