Select file with highest number - batch file

I have a directory full of .jar files, named so gradually:

version-1.jar version-2.jar version-3.jar 

I am trying to select the file with the highest number. Is there any really easy way to do this? Since executing .\version*.jar is causing an error, presumably due to multiple files?

+8
windows batch-file
source share
2 answers

We need a slow expansion

 setlocal enabledelayedexpansion 

Just a variable for maximum:

 set max=0 

Then iterate over the files:

 for %%x in (version-*.jar) do ( 

We need a file name without extension

  set "FN=%%~nx" 

And remove version- from the beginning:

  set "FN=!FN:version-=!" 

Now FN should contain only a number, and we can compare:

  if !FN! GTR !max! set max=!FN! ) 

And you're done:

 echo highest version: version-%max%.jar 

Full batch file:

 @echo off setlocal enabledelayedexpansion set max=0 for %%x in (version-*.jar) do ( set "FN=%%~nx" set "FN=!FN:version-=!" if !FN! GTR !max! set max=!FN! ) echo highest version: version-%max%.jar 
+11
source share

Here is a slightly simpler version than the Joey code.

 @echo off setlocal enableDelayedExpansion set max=0 for /f "tokens=1* delims=-.0" %%A in ('dir /b /ad version-*.jar') do if %%B gtr !max! set max=%%B echo higest version: version-%max%.jar 

This code will work even if the version numbers have a zero prefix, if the version number is never 0 (zero). Specifying tokens = 1 * with 0 included as a separator will remove leading zeros from the version number while storing all zeros after the first non-zero digit.

There is a simpler solution if all versions have a zero prefix with a constant width. But this solution works both with a zero prefix and without it.

Joey code will fail if leading zeros are present, because this indicates octal notation. Invalid octal digits with leading zeros will be treated as strings, as a result of which the comparison will give an incorrect result. This is probably not a problem, since the original question implies that there are no leading zeros. But it's better to be safe than sorry.

+3
source share

All Articles