How can I read the last 2 lines of a file in a batch script

I have a Java program that adds new line information to the last two lines of a file. How can I read them in a batch file?

+4
source share
2 answers

This will solve the problem where someFile.txt is the file in which you want to read the lines:

for /f %%i in ('find /v /c "" ^< someFile.txt') do set /a lines=%%i
echo %lines%
set /a startLine=%lines% - 2
more /e +%startLine% someFile.txt > temp.txt
set vidx=0
for /F "tokens=*" %%A in (temp.txt) do (
    SET /A vidx=!vidx! + 1
    set localVar!vidx!=%%A
)
echo %localVar1%
echo %localVar2%
del temp.txt
+2
source

This code segment does the trick ...

for /F "delims=" %%a in (someFile.txt) do (
   set "lastButOne=!lastLine!"
   set "lastLine=%%a"
)
echo %lastButOne%
echo %lastLine%

EDIT : added full TAIL.BAT

This method can be modified to get more lines that can be specified by the parameter. The following is the tail.bat file :

@echo off
setlocal EnableDelayedExpansion

rem Tail command in pure Batch: Tail.bat filename numOfLines
rem Antonio Perez Ayala

for /F "delims=" %%a in (%1) do (
   set /A i=%2, j=%2-1
   for /L %%j in (!j!,-1,1) do (
      set "lastLine[!i!]=!lastLine[%%j]!
      set /A i-=1
   )
   set "lastLine[1]=%%a"
)
for /L %%i in (%2,-1,1) do if defined lastLine[%%i] echo !lastLine[%%i]!

2ND EDIT: ​​ TAIL.BAT

:

@echo off
setlocal EnableDelayedExpansion

rem Tail command in pure Batch, version 2: Tail.bat filename numOfLines
rem Antonio Perez Ayala

set /A firstTail=1, lastTail=0
for /F "delims=" %%a in (%1) do (
   set /A lastTail+=1, lines=lastTail-firstTail+1
   set "lastLine[!lastTail!]=%%a"
   if !lines! gtr %2 (
      set "lastLine[!firstTail!]="
      set /A firstTail+=1
   )
)
for /L %%i in (%firstTail%,1,%lastTail%) do echo !lastLine[%%i]!
+3

All Articles