Linify
Linify

Reputation: 237

how to increment text filename using batch script

With reference to increment folder name link, I want to ask how to change it from creating folder to creating text file?

Here's the edited version of the code:

@echo off
@For /F "tokens=1,2,3 delims=/ " %%A in ('Date /t') do @( 
    Set Day=%%A
    Set Month=%%B
    Set Year=%%C
)

@echo off
setlocal enableDelayedExpansion
set "baseName=testing-%Year%%Month%%Day%-"
set "n=0"
for /f "delims=" %%F in (
  '2^>nul dir /b /ad "%baseName%*."^|findstr /xri "%baseName%[0-9]*"'
) do (
  set "name=%%F"
  set "name=!name:*%baseName%=!"
  if !name! gtr !n! set "n=!name!"
)
set /a n+=1
md "%baseName%%n%"

So it works like this. "Hello-20140716-1", "Hello-20140716-2" etc folder can be created by double clicking this batch file. But how can I change it from folder to text file?

I tried changing md "%baseName%%n%" to Echo "Hello" > %baseName%%n%.txt and Echo "Bye" > %baseName%%n%".txt

But this does not work as it will only output " Bye" into hello-20140716-1.txt without creating "Hello" to hello-20140716-1.txt and "Bye" to hello-20140716-2.txt

Upvotes: 1

Views: 9711

Answers (2)

Pascal
Pascal

Reputation: 16621

Question title is about 'Increment text filename using batch script', so I dropped the timestamp in filename and just increment the name.

Here is my script:

@echo off
echo.
setlocal

set N=0
set FILENAME=baseFileName.%N%.anyExtension
:loop
set /a N+=1
set FILENAME=baseFileName.%N%.anyExtension
if exist %FILENAME% goto :loop

echo You can safely use this name %FILENAME% to create a new file 

endlocal

Credit:

I created my own flavor based on @foxidrive's answer, meaning 99% credit goes to her/him

Upvotes: 2

foxidrive
foxidrive

Reputation: 41234

Test this:

@echo off
For /F "tokens=1,2,3 delims=/ " %%A in ('Date /t') do @( 
    Set Day=%%A
    Set Month=%%B
    Set Year=%%C
)

set "baseName=testing-%Year%%Month%%Day%-"
set "n=0"
:loop
set /a n+=1
if exist "%baseName%%n%.txt" goto :loop
type nul > "%baseName%%n%.txt"
echo "%baseName%%n%.txt" was created
pause

Upvotes: 2

Related Questions