Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if File Exists and then append Number to Name

Tags:

batch-file

As seen in the title, I am wondering if I can name a .txt file in consequence of a verification of other files that are located in the same folder...

Before even creating my new file, I tried this but it doesn't work since I get an error The system cannot find the file specified. and I can't use Traces!i!.txt as a variable even if I define it later:

@Echo Off 
SETLOCAL EnableDelayedExpansion 
Set dir=C:\...\myFolder\
Set /A i=1 
for /f %%a in ('dir %dir%Traces*.txt /b') do ( 
   Set file=%%a 
   Set /A result=!i! - !file:~6,-4! 
   If "!result:~0,1!"=="-" ( Set /A i=!file:~6,-4! + 1 ) 
   If "!result:~0,1!"=="0" ( Set /A i=!i! + 1 ) 
) 
Echo Traces!i!.txt 
ENDLOCAL 
pause

Also, is there a way that I get the final chosen name as a variable ?

I want the files in my folder to look like:

list1.txt
list2.txt
list3.txt

The next time when I create a new file, its name is supposed to be list4.txt, so I need a program that actually check for other files like I said before.

like image 730
AirfromL Avatar asked Dec 10 '25 20:12

AirfromL


1 Answers

@echo off
setlocal

set "dir=C:\...\myFolder\"
set "i=0"

:get_filename
Set /a "i+=1"
if exist "%dir%Traces%i%.txt" goto :get_filename
set "filename=Traces%i%.txt"

echo "%dir%%filename%"
endlocal
pause

Can just use goto a label to loop to get an indexed filename. Once the 1st indexed filename is not found, filename is set with the value of the indexed filename available for creation.

like image 71
michael_heath Avatar answered Dec 14 '25 03:12

michael_heath



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!