I am writing a batch file in Windows XP. I have copied a set of *.ts
files to the directory of my exe. The number of TS开发者_StackOverflow社区 files are not fixed so as their names.
Now I want to run one of my exe which will take all the TS names as argument.
In Linux I have tried like
<MyExeName> *.ts
This worked. But when I do the same in Windows it's not expanding the *.ts
.
Please let me know how I can expand the *.ts
while passing arguments to my exe.
The Windows shell (command processor) never does any globbing when calling external commands; you have to do it yourself. For C, see Globbing in C++/C, on Windows.
You could use a FOR-Loop to enumarate all *.ts files, like
for %%f in (*.ts) do echo %%f
Near the end of the output from SET /?
is this gem about delayed environment variable extraction. It shows how to use a relatively new notation (since NT 3.1? it works in XP and Win 7) for delayed expansion of an environment variable to build a list of file names matching a wild card in a single variable.
Delayed environment variable expansion allows you to use a different character (the exclamation mark) to expand environment variables at execution time. If delayed variable expansion is enabled, the above examples could be written as follows to work as intended:
set LIST=
for %i in (*) do set LIST=!LIST! %i
echo %LIST%
Note that there is an issue here with quoting of names containing spaces or other "interesting" characters that I've left as an exercise for the student. Getting quoting right in CMD.EXE is even harder than getting it right in any Unix shell.
Naturally, replace the echo
command with your command line.
Edit: It has been observed that this doesn't seem to work as well in a batch file, and it depends on the specific feature of delayed expansion being enabled.
The delayed expansion feature is enabled with the /V:ON
switch to CMD.EXE, or globally for all invocations of CMD by an registry key. The details are documented in the output of CMD /?
.
Moving to a batch file, you have a couple of issues, and an easy fix for enabling the feature. The key is that the SETLOCAL
command has an option to turn the delay feature on and off at will. From CMD /?
:
In a batch file the
SETLOCAL ENABLEDELAYEDEXPANSION
orDISABLEDELAYEDEXPANSION
arguments takes precedence over the/V:ON
or/V:OFF
switch. SeeSETLOCAL /?
for details.
Also, there is the cryptic need to double the percent signs in some contexts, such as FOR
commands. All together, I'd rewrite my example like this:
SETLOCAL ENABLEDELAYEDEXPANSION
set LIST=
for %%f in (*.ts) do set LIST=!LIST! "%%f"
echo %LIST:~1%
The above also quotes each file name to deal with names that have spaces in them, and trims the extra space off the front of the string that was left there by the first loop iteration with %LIST:~1%
.
精彩评论