Splitting a multi-line environment variable into lines

后端 未结 3 2127
耶瑟儿~
耶瑟儿~ 2021-01-23 12:09

I have the following problem: I execute a windows batch file on a Jenkins server and have to split a multi-line environment variable (set vía a Jenkins parameter) into single li

3条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-23 12:24

    You could echo the variable out to a temporary txt file, then process that txt file line-by-line using a for /f loop. You should also use delayed expansion to prevent the line breaks from being evaluated inappropriately.

    @echo off
    setlocal enableDelayedExpansion
    
    :: // Test environment.  Create a variable containing line breaks.
    set BR=^
    
    
    :: // note: The two empty lines above are required.
    set "str=The quick brown!BR!fox jumps over!BR!the lazy dog."
    
    :: // Test environment ready.
    :: // Output to temporary txt file.
    >"%temp%\tmp.txt" echo(!str!
    
    :: // Process the txt file line by line.
    set "line=0"
    for /f "usebackq delims=" %%I in ("%temp%\tmp.txt") do (
        set /a line += 1
        echo Line !line!: %%I
        rem // myprog.exe -baz 0 -meow %%I
    )
    
    :: // Delete temporary txt file.
    del "%temp%\tmp.txt"
    

    That should output

    Line 1: The quick brown

    Line 2: fox jumps over

    Line 3: the lazy dog.


    Or if you'd rather avoid temporary files, you could invoke another runtime to supply the environment variable to a for /f loop. Here's a JScript hybrid example.

    @if (@CodeSection == @Batch) @then
    
    @echo off
    setlocal enableDelayedExpansion
    
    :: // Test environment.  Create a variable containing line breaks.
    set BR=^
    
    
    :: // note: The two empty lines above are required.
    set "str=The quick brown!BR!fox jumps over!BR!the lazy dog."
    
    :: // Test environment ready.
    :: // Invoke JScript to read the environment variable and return it line-by-line
    set "line=0"
    for /f "delims=" %%I in ('cscript /nologo /e:JScript "%~f0"') do (
        set /a line += 1
        echo Line !line!: %%I
    )
    
    :: // end main runtime
    goto :EOF
    
    @end // JScript portion simply echoes %str% from the context of the current process
    WSH.Echo(WSH.CreateObject('WScript.Shell').Environment('PROCESS')('str'));
    

    Output is the same as above.

提交回复
热议问题