Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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?

share|improve this question

2 Answers 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.

share|improve this answer
    
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
up vote 0 down vote accepted

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
)
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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