Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 507
Joshi Avatar asked Dec 11 '14 05:12

Joshi


People also ask

What does @echo off do in a batch file?

To prevent echoing a particular command in a batch file, insert an @ sign in front of the command. To prevent echoing all commands in a batch file, include the echo off command at the beginning of the file.

What is %% K in batch file?

So %%k refers to the value of the 3rd token, which is what is returned.


1 Answers

This code segment do the trick...

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

EDIT: Complete TAIL.BAT added

This method may be modified in order to get a larger number of lines, that may be specified by a parameter. The file below is tail.bat:

@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: New version of TAIL.BAT added

The version below is more efficient:

@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]!
like image 128
Aacini Avatar answered Oct 05 '22 21:10

Aacini