3

I am trying to convert files (movies) in a directory, one by one. Each new, converted file needs a new file name assigned - the old one with a new extension.

I've tried the below to read the source file, strip off the extension and assign a new one:

@echo off
setlocal DisableDelayedExpansion
cd \target_dir
for %%x in (*) do (
  echo %%x
  set source=%%x
  echo Source #%source%#
  set target=%source:.mpg=%
  echo Target #%target%#
  transcode %source% %target%.mp4
)

Unfortunately, this is not working. As the output shows, I am not even managing to copy the current file into the variable "source":

E:\target_dir>..\test.bat
movie1.mpg
source ##
target ##
movie2.mpg
source ##
target ##

I googled around and thought I'd have found the right syntax, but that doesn't appear to be it. Thanks for any help!

2 Answers 2

4

This works:

@echo off
cd \target_dir
for %%x in (*) do (
    transcode "%%x" "%%~nx.mp4"
)

Note that you cannot use the %%~n syntax on standard environment variables - you need to directly access the for loop variable.

Edit: Added quotes to make the batch work with files with spaces in their names as well.

Sign up to request clarification or add additional context in comments.

Comments

3

jlahd shows a correct solution without copying the filename to a variable.

But I want to explain your current problem.

As the output shows, I am not even managing to copy the current file into the variable "source":

You found the BBB (batch beginner bug), in reality you set the variable but you failed to access the content later.

This is an effect of the batch parser working with code blocks, as these blocks are parsed and percent expansion will be done before the code will be executed.
A code block is the code inside of parenthesis or commands concatenated by &, && or ||.

To avoid this problem the delayed expansion was introduced.
Then you simply can use !variable! to expand a variable at runtime.

setlocal EnableDelayedExpansion
cd \target_dir
for %%x in (*) do (
  echo %%x
  set source=%%x
  echo Source #!source!#
  set target=!source:.mpg=!
  echo Target #!target!#
  transcode !source! !target!.mp4
)

1 Comment

Thanks, that helps. I'll nevertheless use @jlahd's solution, as "EnableDelayedExpansion" causes trouble with filenamens including a ! here - at least in the echo, didn't test it any further. Probably because Windows tries to interpret the part after the ! as a variable with this option...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.