I have a directory with a set of subfolder, matching a name pattern, like:


Inside this folders I have some files with the same number on the name as it has been found in the folder name. e.g. the folder sub-123 contains the files


I want to iterate the folder, change the working directory to the current folder, and make some processing with the appropriate set of files. While I can iterate the folders with

for /d %%d in (sub-*) do .

I need the portion of the folder name, what matched the asterisk, in the example above "123". How can I extract the 123 from the folder name and build a command like

cd sub-123
copy input-123 output-123

inside a Windows-7 batch file? In the Linux environment it might be possible to use the cut command or any regular expression. But how should I go in Windows command prompt?


I found it by myself. The set command has an enhanced variable substitution. But it can't be used in the forbody itself. It's necessary to start a new bacth call context:

for /d %%d in (sub-*) do (
  set item=%%d
  pushd %%d
  call :build
goto :eof

  set item=%item:sub-=%
  copy input-%item% output-%item%

The "item" is not exactly build from the string that matched against the asterisk, but it's equivalent.

  • 1
    You might look into delayed variable expansion in the help for 'set' and using ! in lieu of % to get around the need for a new context. – uSlackr May 30 '12 at 18:36
  • I already did and had no success. The problem might be the required variable expandsion, that does not work with the !variable! syntax. You might prove this and correct me when you are successful. – harper May 31 '12 at 4:01

I found also a direct answer. It's near to the cut semantic.

The set command has also a substring syntax. To skip n characters use %variable:~n%. To get n characters starting at offset k use %variable:~k,n%

for /d %%d in (sub-*) do (
  set item=%%d
  set num=%item:~4%
  pushd %%d
  copy input-%num% output-%num%

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.