0

I'm attempting to use a .bat file here and can't quiet get my desired results.

Here's the problem spot:

setlocal enabledelayedexpansion
REM Import our message
set messagelines=0
for /F "tokens=*" %%B in (Myfile.txt) do (
    SET /A messagelines=!messagelines! + 1
    set message!messagelines!=%%B
)
set message

for /L %%C in (1,1,%templatelines%) do (

    REM template%%C defined above
    call :strlen length template%%C

    set string=!message%%C!

    echo !length!

    set string=!string:~0,3!

    REM **** DOESNT WORK ****
    set string=!string:~0,!length!!

    echo !string!
)

REM Finish
exit 1


:strlen <resultVar> <stringVar>
(   
    setlocal EnableDelayedExpansion
    set "s=!%~2!#"
    set "len=0"
    for %%P in (4096 2048 1024 512 256 128 64 32 16 8 4 2 1) do (
        if "!s:~%%P,1!" NEQ "" ( 
            set /a "len+=%%P"
            set "s=!s:~%%P!"
        )
    )
)
( 
    endlocal
    set "%~1=%len%"
    exit /b
)

Everything always displays properly however I am unable to use my length variable to do a substring of my message.

I've tried a few different ways and still am unclear on what to do.

Thanks in advance.

1 Answer 1

2

That line doesn't work because you've got exclamation points inside of exclamation points and batch is matching up the two left and the two right instead of the inner two and outer two. You need to run !length! through a for loop so that the variable will use % symbols:

for %%D in (!length!) do set string=!string:~0,%%D!
Sign up to request clarification or add additional context in comments.

2 Comments

@David - To clarify a bit. If not within the loop, you could use !string:~0,%length%!. But that won't work within the loop because length was defined within the same loop, so %length% will not show the current value. This is the reason delayed expansion must first be used to transfer the value to a FOR variable.
Thanks! I ended up adding the suggested for loop and then using the string variable.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.