Link to home
Start Free TrialLog in
Avatar of ravin1
ravin1

asked on

writing a batch file to get the most recent file

Hi
I am trying to write a batch file that would find the most recent file
in a folder and rename it to recent.csv. All the files in the folder are "CSV" files . I tried the following script exactely but no luck. Can someone tell me what is wrong with then following script. I do not have any experience writing scripts --many thanx
cls
@echo off
dir C:\PERFLOGS /o-d /a-d | find "-" | find ":" > enter.bat
fc enter.bat nul /lb1 /n |date|find " 1: " > enter.bat
echo copy /y %%5.%%6 recent.%%6 > enter.bat
call enter.bat
del enter.bat>nul
cls
ASKER CERTIFIED SOLUTION
Avatar of billious
billious

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of billious
billious

Ah - in the original, you're COPYing the most recent .csv to recent.csv, whereas your request asks for a 'rename'

If you want to COPY (which seems more reasonable) then
replace the 'ren' with 'copy'

A few notes of caution:

1. The if exist .... lines I inserted to warn of the presence of the destination file. Deltet if this is not required.

2. If you do delete those lines, then if the destination file exists and is already open with some utilities (like EXCEL, WORD...) then the copy will fail BECAUSE EXCEL has the file OPEN.

   With some utilities (like WORDPAD, for instance) I believe that the file is loaded into RAM and closed. If you then do your COPY, that will succeed - but the original can still be re-saved from WORDPAD and will then overwrite your newly-copied version.

...Bill

i think you cannot do this with dos-batch-files.
can you think about using perl?

the following perl script will solve your problem:

#!/usr/bin/perl
use File::Basename;
$f = (sort { (stat($b))[9] <=> (stat($a))[9] } <c:/perlflogs/*.*>)[0];
rename $f, (fileparse ($f))[1]."recent.csv" or die $!;

nice work, billious. the FOR options where new for me :-))
ravin1:
This old question needs to be finalized -- accept an answer, split points, or get a refund.  For information on your options, please click here-> http:/help/closing.jsp#1 
EXPERTS:
Post your closing recommendations!  No comment means you don't care.