Vbscript to Obtain the Last N Lines from a Text File

By: nbrane
November 3, 2012

Tail.vbs borrows shamelessy from unix' tail command, and more or less performs the same function: to obtain the last N lines of a textfile (the tail). 
Usage 1 (content is obtained from the filename given on the commandline): 
[cscript] TAIL[.vbs] path+filename startline [numberlines] 
where 'startline' is counted from the end of the file, and numberlines is how many lines to obtain after that  point, and defaults to "through end-of-file"
If your filename happens to be a number, be sure to include a full or relative path in front of it so it will be interpreted as a filename. F/e, if you have a file called 6, or 3.2, refer to it like: .\3.2 or c:\x\6

Usage 2 (content is obtained through the pipe) 
... | CSCRIPT TAIL.VBS startline [numberlines] 
Same idea, but CSCRIPT must be used to launch the vbs, it will not run implicitly. 
3 from end 
2 from end 
1 from end 
tail testfile 3 1 == 3 from end 
tail testfile 3   == 3 from end [crlf]2 from end[crlf]1 from end 
tail testfile 1   == 1 from end 
type testfile | cscript tail.vbs 3 1 == 3 from end 
'======== begin vbscript "tail" 
set fso=createobject("scripting.filesystemobject") 
if argcnt>0 then file=wscript.arguments(0) 
if argcnt>1 then tail=wscript.arguments(1)+1 
select case argcnt 
case 1 
'one arg, only interp as line number, use stdin as file 
 if not isnumeric(file) then wscript.quit 
 on error resume next 
 if b="" then wscript.quit 
case 2 
'two args: file and line, or two lines and stdin for file 
 if isnumeric(file) then 'two numbers 
  on error resume next 
  if b="" then wscript.quit 
  set a=fso.opentextfile(file,1) 'non-number, use as file 
 end if 
case 3 
'easiest: file, line1, line2 
 set a=fso.opentextfile(file,1) 
end select 
for i=1 to tail 
if i=tailend+1 then p2=p 
if p=0 then 
 exit for 
end if 
if p2>0 then c=mid(b,p,p2-p) else c=mid(b,p) 
wscript.echo mid(c,3) 
'======= end vbscript

Need more help?
Describe your Problem
Example: Hard Drive Not Detected on My PC

Ask Question