How to replace value by variable in for + if loop? Nested exclamation marks

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
pstein
Posts: 125
Joined: 09 Nov 2011 01:42

How to replace value by variable in for + if loop? Nested exclamation marks

#1 Post by pstein » 15 Jan 2016 03:30

In a previous helpful post in this forum the following batch code (to determine the lenght of file names) was suggested:

Code: Select all

@echo off
setlocal EnableDelayedExpansion

for /R H:\archive %%f in (*.*) do (
   set "name=%%f"
   if "!name:~100,1!" neq "" (
      for /L %%i in (100,1,500) do if "!name:~%%i,1!" neq "" set /A len=%%i+1
      echo !len!: !name!
   )
)


It works. Unfortunately one of the parameters inside the for loop is a fix value (100).

Now I search for a way to´parameterize it. However the following does NOT work:

Code: Select all

@echo off
setlocal EnableDelayedExpansion
set threshold=100
for /R H:\archive %%f in (*.*) do (
   set "name=%%f"
   if "!name:~!threshold!,1!" neq "" (
      for /L %%i in (:~!threshold!,1,500) do if "!name:~%%i,1!" neq "" set /A len=%%i+1
      echo !len!: !name!
   )
)


I guess because DOS does not accept nested exclamation marks
How else should I rewrite the first code to get it working?

Thank you
Peter

foxidrive
Expert
Posts: 6031
Joined: 10 Feb 2012 02:20

Re: How to replace value by variable in for + if loop? Nested exclamation marks

#2 Post by foxidrive » 15 Jan 2016 03:42

Code: Select all

@echo off
call :routine 5      
pause
goto :eof
:routine
setlocal EnableDelayedExpansion
for /R "H:\archive" %%f in (*.*) do (
   set "name=%%f"
   if "!name:~%1,1!" neq "" (
      for /L %%i in (%1,1,500) do if "!name:~%%i,1!" neq "" set /A len=%%i+1
      echo !len!: !name!
   )
)

pstein
Posts: 125
Joined: 09 Nov 2011 01:42

Re: How to replace value by variable in for + if loop? Nested exclamation marks

#3 Post by pstein » 15 Jan 2016 05:39

Thank you for the solution.
But is this all possible without a (sub)routine/procedure?

Squashman
Expert
Posts: 4486
Joined: 23 Dec 2011 13:59

Re: How to replace value by variable in for + if loop? Nested exclamation marks

#4 Post by Squashman » 15 Jan 2016 07:16

I am not understanding why you are using delayed expansion for the threshold variable? :?:

foxidrive
Expert
Posts: 6031
Joined: 10 Feb 2012 02:20

Re: How to replace value by variable in for + if loop? Nested exclamation marks

#5 Post by foxidrive » 15 Jan 2016 08:20

Good point.

This is wrong too: :~!threshold!

pstein
Posts: 125
Joined: 09 Nov 2011 01:42

Re: How to replace value by variable in for + if loop? Nested exclamation marks

#6 Post by pstein » 16 Jan 2016 08:50

Ok, seems to work

Thank you

Post Reply