Question

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%
Was it helpful?

Solution

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"

OTHER TIPS

The for command is quite powerful nowadays:

for /F "skip=4 delims=" %i in (test.txt) do echo %i

Skip the first 4 lines, leaving the 5th line effectively. No delimiters, so that you get the complete line and not only the first token of that line.

Replace echo %i by anything you want to do with the 5th line.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top