4

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

sub-123
sub-0815
sub-4711

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

input-123
output-123

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?

2 Answers 2

2

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
  popd
)
goto :eof

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

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

2
  • 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, 2012 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, 2012 at 4:01
1

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%
  popd
)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .