Dos Batch - For Loop
can anyone tell me why in the example below the value of LIST is always blank i would also like to only retrive the first 4 characters of %%i in variable LIST
cd E:\Department\Finance\edi\Japan_orders\
FOR /f %%i IN ('dir /b *.*') DO (
copy %%i E:\Department\Finance\Edi\commsfile.txt
开发者_如何学编程
set LIST=%%i
echo %LIST%
if %%i == FORD110509 CALL E:\Department\Finance\edi\EXTRACT.exe E:\Department\Finance\edi\COMMSFILE.TXT
)
pause
thanks in advance
You need delayed expansion. Add the following at the start of your program:
setlocal enabledelayedexpansion
and then use !LIST!
instead of %LIST%
inside of the loop.
For a thorough explanation please read help set
.
Bracketed command blocks are parsed entirely, and it is done prior to their execution. Your %LIST%
expression, therefore, is expanded at the beginning, while the LIST
variable is still empty. When the time comes to execute echo %LIST%
, there's not %LIST%
any more there, only the empty string (read: 'nothing') instead. It's just how it works (don't ask me why).
In such cases the delayed expansion mechanism is used, and Joey has already told you that you need to use a special syntax of !LIST!
instead of %LIST%
, which must first be enabled (typically, by the command SETLOCAL EnableDelayedExpansion
, which he has mentioned as well).
On your other point, you can extract a substring from a value, but the value must first be stored into a variable. Basically, the syntax for extracting substrings is one these:
%VARIABLE:~offset,charcount%
%VARIABLE:~offset%
That is, you are to specify the starting position (0-based) and, optionally, the number of characters to cut from the value. (If quantity
is omitted then you are simply cutting the source string at the offset to the end.) You can read more about it by issuing HELP SET
from the command line (wait, it's the same command that Joey has mentioned!).
One more thing: don't forget about the delayed expansion. You need to change the above %
syntax to the !
one. In your case the correct expression for retrieving the first 4 characters would be:
!LIST:~0,4!
You can use it directly or you could first store it back to LIST
and then use simply !LIST!
wherever you need the substring.
精彩评论