user3668129
user3668129

Reputation: 4820

How to get last file name in dir command?

I have a log folder, with files in the following names:

number.txt (example: 1.txt 3.txt 55.txt ...)

The name (number) not necessarily means the that it is latest date.

I want to write a batch script (.bat) which get the biggest file number and create a new text file with next number (if the biggest file number was X, I want to create a new text file with the name X+1)

for example:

Suppose we have those files in the log folder:

1.txt 
5.txt
99.txt

After running the script (.bat) a new file 100.txt need to be created

How can I do it ?

Upvotes: 0

Views: 1707

Answers (2)

user7818749
user7818749

Reputation:

I don't really support off topic questions, but this is really not rocket science:

@echo off
setlocal enabledelayedexpansion
set cnt=0
for %%i in (*.txt) do (
    set "num=%%~ni"
    if !num! GTR !cnt! set cnt=!num!
)
set /a newfile=cnt+1
type nul > %newfile%.txt

It is really straight forward. We set a counter of 0 (cnt=0).

Loop through all files and remove the extension by using only the name from the token (%%~ni), so we have only the number left ad assign it to a variable num=%%~ni.

Then we match the file number with the counter, if the file number is greater than the the counter, we set the counter number to that same value, until we looped to the highest number, then simply take that value +1 and create the file by type nul > newnumber.txt

See loads of help around the commands used by simply running for /?, if /?, set /? and setlocal /? from cmd.exe terminal window.

Upvotes: 2

Aacini
Aacini

Reputation: 67216

"How can I do it?" is not a valid question here... However, I do it this way:

@echo off

for %%i in (*.txt) do set /A "i=%%~Ni-next+1,next+=((i>>31)+1)*i"
rem/>%next%.txt

Upvotes: 3

Related Questions