Batch File: Alphabetically Last File Name

April 26, 2009 at 07:41:07
Specs: Windows XP, C2D 1.66 Ghz
Hello.

I would like to write a batch file to return the the alphabetically last filename in a given directory. There are no subdirectories, just a bunch of files in one directory.

I would appreciate help.

Thanks.


See More: Batch File: Alphabetically Last File Name

Report •


#1
April 26, 2009 at 12:24:57
:: LASTFILE.BAT Usage: lastfile Folder_Name
@echo off & setlocal
pushd %*
for /F "delims=" %%j in ('dir /B /ON /A-D') do set LastFile=%%j
echo.  %LastFile%
popd
:: End_Of_Batch

If you need file's size and time, add at the end of the For /F statement

%%~zj %%~tj


Report •

#2
April 26, 2009 at 13:58:22
Can you explain what the loop does? As far as I understand it orders the files alphabetically and loops through all of them until it gets to the last one, assigning each one to the variable, so the variable ends up with the name of the last file.

Wouldn't it be faster to order the files reverse alphabetically, and have the code fragment break out of the loop as soon as it does its first assignment, with a GOTO or something?

I think I have the logic of it down but I'm not very good with syntax. I would appreciate your help.


Report •

#3
April 26, 2009 at 14:47:02
:: LASTFILE.BAT Usage: lastfile Folder_Name
@echo off & setlocal
pushd %*
for /F "delims=" %%j in ('dir /B /O-N /A-D') do (
  LastFile=%%j
  goto :DONE
)
:DONE
echo.  %LastFile%
popd
:: End_Of_Batch
 


Report •

Related Solutions

#4
April 26, 2009 at 15:12:17
'LastFile' is not recognized as an internal or external command,
operable program or batch file.

An oopsie - twice... LOL


Report •

#5
April 27, 2009 at 01:20:07
Sorry, that has to be replaced with

  set LastFile=%%j

I am surprised you, so able to spell my script and suggest an optimized variant, can not correct a so basic mistake.

Report •

#6
April 27, 2009 at 10:12:24
The person who was rude about your syntax error is someone else, posting from a different username. I would not be so rude as to make fun of someone who is helping me. Besides, as you said, the error is trivial and easily found and fixed.

Thank you for your assistance.


Report •

#7
April 27, 2009 at 12:37:25
Hi transitionality,

I apologize I have not noticed the poster's nickname.

Usually I test the scripts I post, but sometime the time lacks or I am too confident with easy code and failure never sleeps.

Anyway I don't love people that require scripts lacking ever the basic fundamentals. Help yourself if you need any help. Obviously this is not your case, but Forums are plagued by such a kind of people.


Report •


Ask Question