Splitting a multi-line environment variable into lines

后端 未结 3 2123
耶瑟儿~
耶瑟儿~ 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:32

    The FOR /F command takes the LF's inserted in the variable as lines separators (this is the natural behavior of FOR /F command), so nothing additional is required in order to process such variable with FOR /F:

    @echo off
    setlocal EnableDelayedExpansion
    
    rem Create a variable containing line breaks.
    set LF=^
    %empty line 1/2%
    %empty line 2/2%
    set "str=The quick brown!LF!fox jumps over!LF!the lazy dog."
    
    set line=0
    for /F "delims=" %%a in ("!str!") do (
       set /A line+=1
       echo Line !line!: %%a
    )
    

    The key here is expanding the variable with !exclamationMarks!; otherwise the LF will cut the %value%. Also, if you want complete lines separated by LF, use "delims=". Output example:

    Line 1: The quick brown
    Line 2: fox jumps over
    Line 3: the lazy dog.
    

提交回复
热议问题