Windows Script Package - Reading Filenames in Variables

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

I tried below to read the original file, disable 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 doesn't work. As the output shows, I can't even copy the current file to the "source" variable:

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

      

I googled around and thought I found the correct syntax, but it doesn't seem to be the case. Thanks for any help!

+3


source to share


2 answers


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

But I want to explain your current problem.

As the output shows, I can't even copy the current file to the "source" variable:

You found a BBB (initial beginner error), in fact you set a variable, but later on you were unable to access the content.



This is the effect of a parser parser working with blocks of code, since these blocks are parsed and the percentage expansion will be executed before the code is executed.
A code block is a code within brackets or a command, combined &

, &&

or ||

.

To avoid this problem, delayed expansion was introduced.
Then you can just use !variable!

to expand the 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
)

      

+2


source


It works:

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

      



Note that you cannot use the syntax %%~n

for standard environment variables - you need to access the for loop variable directly.

Edit: added quotes to allow batching files with spaces in their names.

+4


source







All Articles