[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 5577
  • Last Modified:

"tail -1" equivalent in Windows?

Is there a way to read the last line of text file using a Windows batch file?  I essentially want to use the equivalent of "tail -1" in *NIX.  I eventually want to read the last line of each file in a specific subdirectory, or read the last line of a file on a group of workstations.
0
jclingensmith
Asked:
jclingensmith
1 Solution
 
SteveGTRCommented:
You could do this:

@echo off

setlocal

set lastLine=

for /f "tokens=*" %%a in ('type "%~1"') do set lastLine=%%a

echo Last line: %lastLine%

This batch file will accept the name of the file where you want the last line as a command line parameter.

You could adapt this processing to read the last line of all files in a directory like so:

@echo off

setlocal

set workDir=.

if not "%~1"=="" set workDir=%~1
if not exist "%workDir%" echo %~1 does not exist&goto :EOF

pushd "%workDir%"

for /f "tokens=*" %%a in ('dir /b /a-d') do call :GETLASTLINE "%%a"

popd

goto :EOF

:GETLASTLINE

set lastLine=

for /f "tokens=*" %%a in ('type "%~1"') do set lastLine=%%a

echo File: %~1 Last line: %lastLine%
0
 
basicinstinctCommented:
install Cygwin and then ue the tail command

http://www.cygwin.com/
0
 
basicinstinctCommented:
windows apparently does have a tail command, it comes as part of a resource kit that you can install on XP:

http://malektips.com/xp_dos_0001.html
0
 
ghostdog74Commented:
here's a simple vbscript to simulate tail.

On Error Resume Next
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set wshArgs = WScript.Arguments
If wshArgs(0) = "" Or wshArgs(1) = "" Then
      WScript.Echo "Usage: cscript /nologo " & Wscript.ScriptName & " <tail number> filename "
      WScript.Quit(1)
End If
myTailNum = wshArgs(0)
myFile = wshArgs(1)
Set objFile = objFSO.OpenTextFile(myFile,1)
For k=0 To myTailNum
      objFile.SkipLine
Next
Do Until objFile.AtEndOfStream
      WScript.Echo objFile.ReadLine
Loop


usage: cscript /nologo tail.vbs 10 file
0
 
MaasdrielCommented:
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now