Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open one of a series of files using a batch file

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.

like image 412
Keng Avatar asked Sep 09 '08 13:09

Keng


People also ask

What does %% A mean in batch?

%%a refers to the name of the variable your for loop will write to. Quoted from for /? : FOR %variable IN (set) DO command [command-parameters] %variable Specifies a single letter replaceable parameter. (set) Specifies a set of one or more files. Wildcards may be used.

How do you make a batch file that opens a shortcut?

If you want to use a custom file icon for your batch file, we recommend using a shortcut. Right-click the desktop and select New > Shortcut. Choose a location, ideally the same as your batch file, and click Next. Then enter a name for the shortcut and click Finish.

What does && do in batch file?

&& runs the second command on the line when the first command comes back successfully (i.e. errorlevel == 0 ). The opposite of && is || , which runs the second command when the first command is unsuccessful (i.e. errorlevel != 0 ).


1 Answers

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.

like image 103
Paulius Avatar answered Oct 21 '22 04:10

Paulius