Reading a specific line in a text file to a variable in a batch file

user2997654 picture user2997654 · Mar 10, 2014 · Viewed 43.5k times · Source

In one of my batch files I'm attempting to write, I need to read the last line in a 5 line text file into a variable. One way I thought of doing this might be to have each line that is put into the text file overwrite the previous (as the files creation and lines are all created by a command, specifically slmgr /xpr) but I'm not sure how to do this. Any suggestions or alternate ways of doing this are appreciated!

cscript %windir%\system32\slmgr.vbs /xpr > xprtest.txt
pause
for /F "skip=4 delims=" %i in (xprtest.txt) set /p xprvar= <xprtest.txt
pause
echo %xprvar%

Answer

Magoo picture Magoo · Mar 10, 2014

if you want specifically line 5:

set "xprvar="
for /F "skip=4 delims=" %%i in (xprtest.txt) do if not defined xprvar set "xprvar=%%i"

OR

for /F "skip=4 delims=" %%i in (xprtest.txt) do set "xprvar=%%i"&goto nextline
:nextline

if you want the last line regardless of the number of lines:

for /F "delims=" %%i in (xprtest.txt) do set "xprvar=%%i"