i3i5i7
i3i5i7

Reputation: 130

Windows Batch Script - Read file names into variables

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!

Upvotes: 3

Views: 15286

Answers (2)

jeb
jeb

Reputation: 82307

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
)

Upvotes: 3

jlahd
jlahd

Reputation: 6293

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.

Upvotes: 4

Related Questions