mrcoulson
mrcoulson

Reputation: 1403

How do I save a specific line of command output as a variable on Windows?

Consider this .bat file:

@ECHO OFF

ECHO Owner: Jeremy.Coulson
ECHO Food: Ham sandwiches
ECHO Drink: Lemonade

Consider this second .bat file:

@ECHO OFF

FOR /F "tokens=*" %%a in ('source.bat') do SET OUTPUT=%%a
echo %output%

The result of running the second .bat file is:

Drink: Lemonade

Clearly, what I'm doing here is only getting the last thing output by source.bat. What if instead, I wanted to specify which line to retrieve as the variable? What if, for example, I want to retrieve only whatever is on the "Food" line?

Upvotes: 0

Views: 1822

Answers (2)

aschipfl
aschipfl

Reputation: 34909

  1. To get the line containing a specific word, pipe (|) the output into find (remove the /I from find to do a case-sensitive search):

    for /F "delims=" %%L in ('call source.bat ^| find /I "Food"') do (
        set OUTPUT=%%L
        REM goto :CONTINUE
    )
    :CONTINUE
    

    If there could be multiple matches, you need to decide: if you want the first match, remove the REM in front of goto; if you want the last, leave it.

  2. To get a certain line number, simply specify the skip option of for /F:

    set "NUMBER=4"
    set /A "SKIP=NUMBER-1"
    if %SKIP% leq 0 set "SKIP=" else set "SKIP=skip=%SKIP% "
    for /F "%SKIP%delims=" %%L in ('call source.bat') do (
        set OUTPUT=%%L
        goto :CONTINUE
    )
    :CONTINUE
    

    SKIP will contain skip=3 in the above example (with a trailing SPACE, so for /F receives "skip=3 delims="). The if clause ensures that SKIP is empty in case 0 or less numbers are specified to be skipped, because for /F throws a syntax error in case skip=0 is given.

Upvotes: 2

Squashman
Squashman

Reputation: 14290

Just use FIND instead.

@ECHO OFF

FOR /F "tokens=*" %%a in ('find /I "Drink:" ^<source.txt') do SET OUTPUT=%%a
echo %output%

Upvotes: 1

Related Questions