# Finding first file name in dir



## bkolb (Mar 11, 2010)

I have a directory with several files in it that look alike except for the date that's part of the filename. Like this:

text_file_2010-03-01.txt
text_file_2010-02-28.txt
text_file_2010-03-02.txt
text_file_2010-02-27.txt
text_file_2010-02-24.txt
text_file_2010-02-02.txt
text_file_2010-02-21.txt
text_file_2010-02-08.txt

In effect, I want to sort these in decreasing order and return the top filename. So they'd be sorted like this:

text_file_2010-03-02.txt
text_file_2010-03-01.txt
text_file_2010-02-28.txt
text_file_2010-02-27.txt
text_file_2010-02-24.txt
text_file_2010-02-21.txt
text_file_2010-02-08.txt
text_file_2010-02-02.txt

and only the file name "text_file_2010-03-02.txt" would be returned, which I would then use for other processing. 

any ideas?


----------



## bkolb (Mar 11, 2010)

Forgot to mention, I know how to sort them so the file I want is on top (dir file_name_*.txt /O:-N) but how do I pull only that first name off and return it?


----------



## Squashman (Apr 4, 2003)

Couple of ways to do it.
Output the list to a temp file then redirect the file to a variable.
dir file_name_*.txt /a-d /b /O-N>temp.txt
set /p _FirstFile=<temp.txt
del temp.txt

You could also put it into a for loop and then kill the for loop immediately with a Goto.


----------



## Squashman (Apr 4, 2003)

Or as TheOutCaste pointed out, you can do a normal alphabetical list and the last file will get assigned in a loop.

```
For /F "Tokens=*" %%I In ('dir file_name_*.txt /a-d /b /ON') do Set _FName=%%I
```


----------

