DOS script to output contents of latest file matching a given spec

Some of our batch jobs write log information to standard output. Others create dated log files.

Our scheduling tool kind of works best if log information goes to standard output – it captures it then allows you to inspect it from console.

I wrote the following script to spool out the latest version of a given dated log file.

I called it show_log.bat So if you run it as follows:

cmd /k show_log d:logfilesmy_batch_job_*.log

…it displays the latest my_batch_job_*.log that it can find, where * is any string – in our case typically a date of some sort. So I put a call to show_log at the end of each batch job which creates a dated log file and I can see it from the scheduler console too.

If you have a directory that is called my_batch_job_*.log it wouldn’t work so well – I had to use /S to get dir to return the full pathname for the file.

echo off

rem This routine accepts a file specification (in the
rem format you use for rem dir)
as a paremeter, then
rem displays the last updated file matching that

rem specification to stdout
rem It replaces

set DIR_STRING=”%1″
echo Dir String %DIR_STRING%

rem These couple of lines work out what the last
rem updated file is.
The dir command orders by
rem the updated date. The /S means do a
rem search. This is there to ensure that the dir
rem returns the full path
name rather than to
rem actually search a directory structure.
rem We would get
unexpected results if the
rem dir_string does actually match

rem a directory.

for /f %%I in (‘dir /B /N /S /OD %DIR_STRING% ‘) do set LAST_FILE=%%I
echo Last file is %LAST_FILE%

if “%LAST_FILE%”==”” exit

rem Retreiving the date stamp of the file for display

for /f “tokens=1,2” %%I in (‘dir %LAST_FILE% ^| findstr /V “Volume Directory ( ^$”‘) do set DATE_CREATED=%%I %%J
echo Date created is %DATE_CREATED%

echo Going to output this file:
dir %LAST_FILE% | findstr /V “Volume Directory ( ^$”
echo —–

rem Echoing line by line rather than simply using
rem ‘type’ because I wanted
to prefix each line
rem with the files datestamp. The reason for this is

rem because I don’t want there to be any confusion
rem as to what file is
being looked at, either
rem because this script has failed or because

rem the file you’re expecting hasn’t actually
rem been created

for /F “delims=” %%I in (%LAST_FILE%) do echo %DATE_CREATED% Log: %%I