Return last line of text file

  • Thread starter Thread starter Anthony Lizza
  • Start date Start date
A

Anthony Lizza

Hi,

is it possible for a batch to file to read through a small text file and
echo back the last line?

Thanks
 
This will echo the last line of test.txt that is not an empty line.

@echo off & setlocal enabledelayedexpansion
for /f "tokens=*" %%c in (test.txt) do (
set temp=%%c
)
echo !temp!

There are existing utils for this like TAIL.
 
Anthony Lizza said:
Hi,

is it possible for a batch to file to read through a small text file and
echo back the last line?

Thanks
Two ways: file name is expected as first argument of the batch

@echo off & setlocal
if not exist %1 echo File not found & goto :eof
for /f "delims=" %%A in (%1) do set line=%%A
echo/%line%

@echo off & setlocal enabledelayedexpansion
if not exist %1 echo File not found & goto :eof
for /f "delims=" %%A in ('find /C /V "" ^<%1') do (set /A offset=%%A -1
more +!offset! <%1)

HTH
 
Hi Anthony,
Anthony said:
is it possible for a batch to file to read through a small text file
and echo back the last line?

or with VBScript:(I shorted a hit from an older thread):

myFile = wscript.arguments(0)
Set fso = CreateObject("Scripting.FileSystemObject")
Const ForReading = 1
Set s = fso.OpenTextFile(myFile, ForReading)

Do until s.AtEndOfStream
LastLine = s.ReadLine
Loop

wscript.echo LastLine
wscript.quit

Best greetings from Germany
Olaf.
 
Hi,

is it possible for a batch to file to read through a small text file and
echo back the last line?

Thanks
call lastline filename

or

for /f "TOKENS=*" %%a in ('lastline FileName') do (
set Line=%%a
)

where lastline.bat contains:

@echo off
if {%1}=={} @echo Syntax: LastLine FileName&goto :EOF
if not exist %1 echo LastLine: File %1 not found.&goto :EOF
setlocal ENABLEDELAYEDEXPANSION
for /f "delims=" %%L in ('find /C /V "" <%1') do (
set /A offset=%%L -1
more +!offset! <%1
)
endlocal



Jerold Schulman
Windows: General MVP
JSI, Inc.
http://www.jsiinc.com
 
Back
Top