Batch File: How can I have a function return a value when the parameter passed to that function contains spaces?

醉酒当歌 提交于 2019-12-24 20:58:49

问题


I will try to explain as clearly as possible. My scenario starts with a txt file, cases.txt, that contains two lines:

line1 () CASE1
line2 () CASE 2

The batch file iterates through that file using a FOR loop and passes each line to a function, find_index, that extracts (and should return) the location of the ')' character. Here is the code that I can't get working:

@ECHO off
SETLOCAL ENABLEDELAYEDEXPANSION

FOR /f "delims=" %%a IN (cases.txt) DO (
    ECHO %%a
    CALL :find_index %%a INDEX
    ECHO Found index at !INDEX!
)
GOTO :EOF

:find_index
    set S=%*
    set I=0
    set L=-1
    :l
        if "!S:~%I%,1!"=="" goto ld
        if "!S:~%I%,1!"==")" set L=%I%
        set /a I+=1
        goto l
    :ld
        SET %2 = %L%
        ECHO %2
        GOTO :EOF

What I want to happen is that the "INDEX" being passed to the function gets assigned the value of the result which I can then use for further operations (which I have yet to script because I'm stuck). What happens is that %2 gets assigned with the value of the second word in the string () which being passed as a parameter to the function. Sample output is:

line1 () CASE1
()
Index is at
line2 () CASE 2
()
Index is at

Expected output is for ECHO %2 to return 7 and for the final output to read Index is at 7

What am I doing wrong? Any help would be greatly appreciated!

Thank you!

Andrew


回答1:


In your script, from the very beginning to the end the variable !INDEX! is not defined anywhere. Your index value is actually being stored in the variable !L! and you don't need that function :ld. See below modified script and sample output.

@ECHO off
SETLOCAL ENABLEDELAYEDEXPANSION

FOR /f "delims=" %%a IN (cases.txt) DO (
    ECHO %%a
    CALL :find_index %%a INDEX
    ECHO Found index at !L!
)
GOTO :EOF

:find_index
    set S=%*
    set I=0
    set L=-1
    :l
        if "!S:~%I%,1!"=="" goto :EOF
        if "!S:~%I%,1!"==")" set L=%I%
        set /a I+=1
        goto l
        GOTO :EOF

Tested output -

D:\Scripts>type cases.txt
line1 () CASE1
line2 () CASE 2
sometext () case3
D:\Scripts>
D:\Scripts>
D:\Scripts>
D:\Scripts>draft.bat
line1 () CASE1
Found index at 7
line2 () CASE 2
Found index at 7
sometext () case3
Found index at 10

Cheers, G



来源:https://stackoverflow.com/questions/25563093/batch-file-how-can-i-have-a-function-return-a-value-when-the-parameter-passed-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!