0

I am trying to do something nearly identical to this: How do I increment a folder name using Windows batch?

Essentially, I want to create a batch file to scan through a directory, determine the highest version number, and then create the next one in sequence. So if the directory contains:

New folder V1.0
New folder V1.1
New folder V1.3

I want the batch file to add a New folder V1.4. Should be doable. The problem is that the script I found:

@echo off
setlocal enableDelayedExpansion
set "baseName=New_Folder"
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%"

doesn't work with folders with spaces in the name IE it works with 'New_Folder' but not 'New Folder'. I've tried escaping the spaces with various permutations of ^ and ", for example,

set "baseName=New^ Folder"
set "baseName=New" "Folder"
set "baseName=New""^ ""Folder"

and so forth, however, I haven't gotten it to work.

I am aware that I could solve the problem by changing my file names to use underscores, but at this point, I want to know why it doesn't work and how to fix it.

Community
  • 1
  • 1
Firnagzen
  • 1,212
  • 3
  • 13
  • 29

1 Answers1

4

This works here.

@echo off
setlocal enableDelayedExpansion
set "baseName=New Folder V1."
set "n=0"
for /f "delims=" %%F in (
  '2^>nul dir /b /ad "%baseName%*"^|findstr /xri /c:"%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%"
foxidrive
  • 40,353
  • 10
  • 53
  • 68
  • 1
    ... Ok, that works. *How* does it work? Doesn't /c specify a literal string? – Firnagzen Jun 26 '13 at 13:27
  • /c doesn't specify a literal string, it specifies the search term. In this case, it's the /r that tells findstr that the text in the /c parameter should be treated as a regular expression. – Mark Jun 26 '13 at 16:46
  • I see. So why doesn't it work without the /c? Shouldn't the double quotes escape the space so the entire thing gets read as a single string? – Firnagzen Jun 27 '13 at 02:31
  • findstr takes "foo bar" without the /c as two search strings of foo and bar. – foxidrive Jun 27 '13 at 02:55