1. Computer problem? Tech Support Guy is completely free -- paid for by advertisers and donations. Click here to join today! If you're new to Tech Support Guy, we highly recommend that you visit our Guide for New Members.

Finding first file name in dir

Discussion in 'DOS/Other' started by bkolb, Mar 11, 2010.

Thread Status:
Not open for further replies.
Advertisement
  1. bkolb

    bkolb Thread Starter

    Joined:
    Mar 11, 2010
    Messages:
    2
    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?
     
  2. bkolb

    bkolb Thread Starter

    Joined:
    Mar 11, 2010
    Messages:
    2
    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?
     
  3. Squashman

    Squashman Trusted Advisor

    Joined:
    Apr 4, 2003
    Messages:
    19,731
    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.
     
  4. Squashman

    Squashman Trusted Advisor

    Joined:
    Apr 4, 2003
    Messages:
    19,731
    Or as TheOutCaste pointed out, you can do a normal alphabetical list and the last file will get assigned in a loop.
    Code:
    For /F "Tokens=*" %%I In ('dir file_name_*.txt /a-d /b /ON') do Set _FName=%%I
     
As Seen On
As Seen On...

Welcome to Tech Support Guy!

Are you looking for the solution to your computer problem? Join our site today to ask your question. This site is completely free -- paid for by advertisers and donations.

If you're not already familiar with forums, watch our Welcome Guide to get started.

Join over 733,556 other people just like you!

Loading...
Thread Status:
Not open for further replies.

Short URL to this thread: https://techguy.org/909370