Brian
Brian

Reputation: 319

Assign Last Two Lines of Text as Variable via Batch Script

Hi I have a text file in which I need to use the last two lines as two variables in a batch script. Example:

file.txt contains:

Release2010
Release2011
Release2013

I need var1 = Release2011 and var2 = Release2013. The length of the file will vary but I will always need the last two lines.

Thanks for your assistance!

Upvotes: 1

Views: 494

Answers (2)

Endoro
Endoro

Reputation: 37569

you might try this:

@ECHO OFF &SETLOCAL ENABLEDELAYEDEXPANSION
FOR /f "delims=" %%a IN (file) DO (
    SET "var2=!var1!"
    SET "var1=%%a"
)
ECHO(var1: %var1%
ECHO(var2: %var2%

and the same without delayed expansion:

@ECHO OFF &SETLOCAL
FOR /f "delims=" %%a IN (file) DO (
    CALL SET "var2=%%var1%%"
    SET "var1=%%a"
)
ECHO(var1: %var1%
ECHO(var2: %var2%

Upvotes: 2

RGuggisberg
RGuggisberg

Reputation: 4750

Here's one way to do it without enabling delayed expansion.

@ECHO OFF
FOR /F %%A IN (InFile.txt) DO (
   CALL :SetSecondLastLine
   SET LastLine=%%A
   )
ECHO.SecondLastLine=%SecondLastLine%
ECHO.LastLine=%LastLine%
pause
GOTO :eof

:SetSecondLastLine
SET SecondLastLine=%LastLine%
GOTO:EOF

Upvotes: 0

Related Questions