Search code examples
windowsbatch-filefilenames

Batch: Return filename with highest integer


If I have a directory full of text files such as

01.text.sql
02text.sql
3text.sql

how would I return the file name with the highest integer e.g. 3.text.sql? As you can see the numbers might not be prefixed with 0 and might be missing a . after the integer. I know I have to loop through the directory with something like this

Choose Highest Numbered File - Batch File

however, this does not take into account different file name formats. Is there any way a batch script can loop through a directory and automatically pull the file with the highest integer or do I have to store the file names and compare them with each other in a separate loop?

Currently I have something like this but it returns 3text instead of just 3

SETLOCAL enabledelayedexpansion
SET max=0
FOR %%x in (*.sql) DO (
  SET "FN=%%~nx"
  SET "FN=!FN:*-=!"
  IF !FN! GTR !max! SET max=!FN!
)
ECHO Highest script number is %max%

Updated loop:

SETLOCAL enabledelayedexpansion
SET scriptmax=0
FOR %%x in (*.sql) DO (
  SET "FN=%%~nx"
  SET a=1000!FN!
  SET /A FN=a %% 1000
  IF !FN! GTR !max! SET max=!FN!
)

Solution

  • set /A a=b will interpret everything in b up to the first non numeric character as a number, so

    set FN=03text.txt
    set /A a=FN
    

    will set %a% nicely to 3. But we have an additional problem here: Numbers prefixed with a 0 will be interpreted as octal, so 08 and 09 are illegal. To fix this:

    set FN=09text.txt
    set t=1!FN!
    set /A a=t-100
    

    will yield 9.

    However, this will only work if you know how many digits to expect, maybe you have to check for a leading zero first (if "%FN:~0,1%" == "0" ...), and/or even chop off leading zeroes (set FN=%FN:~1%)

    Edit: a better way:

    set FN=09text.txt
    set a=1000!FN!
    set /A FN=a %% 1000
    

    will work for anything up to 999.