Open one of a series of files using a batch file

2019-02-17 12:24发布

问题:

I have up to 4 files based on this structure (note the prefixes are dates)

  • 0830filename.txt
  • 0907filename.txt
  • 0914filename.txt
  • 0921filename.txt

I want to open the the most recent one (0921filename.txt). how can i do this in a batch file?

Thanks.

回答1:

This method uses the actual file modification date, to figure out which one is the latest file:

@echo off
for /F %%i in ('dir /B /O:-D *.txt') do (
    call :open "%%i"
    exit /B 0
)
:open
    start "dummy" "%~1"
exit /B 0

This method, however, chooses the last file in alphabetic order (or the first one, in reverse-alphabetic order), so if the filenames are consistent - it will work:

@echo off
for /F %%i in ('dir /B *.txt^|sort /R') do (
    call :open "%%i"
    exit /B 0
)
:open
    start "dummy" "%~1"
exit /B 0

You actually have to choose which method is better for you.



回答2:

Sorry, for spamming this question, but I just really feel like posting The Real Answer. If you want your BATCH script to parse and compare the dates in filenames, then you can use something like this:

@echo off

rem Enter the ending of the filenames.
rem Basically, you must specify everything that comes after the date.
set fn_end=filename.txt

rem Do not touch anything bellow this line.
set max_month=00
set max_day=00

for /F %%i in ('dir /B *%fn_end%') do call :check "%%i"
call :open %max_month% %max_day%
exit /B 0

:check
    set name=%~1
    set date=%name:~0,4%
    set month=%date:~0,2%
    set day=%date:~2,2%
    if /I %month% GTR %max_month% (
        set max_month=%month%
        set max_day=%day%
    ) else if /I %month% EQU %max_month% (
        set max_month=%month%
        if /I %day% GTR %max_day% (
            set max_day=%day%
        )
    )
exit /B 0

:open
    set date=%~1
    set month=%~2
    set name=%date%%month%%fn_end%
    start "dummy" "%name%"
exit /B 0


回答3:

One liner, using EXIT trick:

FOR /F %%I IN ('DIR *.TXT /B /O:-D') DO NOTEPAD %%I & EXIT

EDIT:

@pam: you're right, I was assuming that the files were in date order, but you can change the command to:

FOR /F %%I IN ('DIR *.TXT /B /O:-N') DO NOTEPAD %%I & EXIT

then you have the file list sorted by name in reverse order.



回答4:

Here you go... (hope no-one beat me to it...) (You'll need to save the file as lasttext.bat or something) This will open up / run the oldest .txt file

dir *.txt /b /od > systext.bak 
FOR /F %%i in (systext.bak) do set sysRunCommand=%%i 
call %sysRunCommand%
del systext.bak /Y

Probably XP only. BEHOLD The mighty power of DOS.
Although this takes the latest filename by date - NOT by filename..

If you want to get the latest filename, change /od to /on .
If you want to sort on something else, add a "sort" command to the second line.



回答5:

Use regular expression to parse the relevant integer out and compare them.