0

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?

2 Answers 2

2
  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.

Sign up to request clarification or add additional context in comments.

1 Comment

In this case, I only expect one match, but it's awesome to see what to do when I expect multiple. Thanks!
1

Just use FIND instead.

@ECHO OFF

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.