1

I would like to create a batch-file that reads the first 10 file names in a spefic directory, and then sets the paths to 10 different variables. For a simple example, the path would be c:\test and inside there, there would be lots of files named file1.tif, file2.tif, etc. I would like to set the variable filepath1 equal to the path of the 1st file, which would be c:\test\file1.tif, and so on for the first 10 files. Here is the code:

@echo off
cd C:\TEST
setlocal ENABLEDELAYEDEXPANSION
FOR /f "delims=|" %%a IN ('dir /b') DO (
    CALL SET /a x = !x! +1
    if !x! == 1 (
        CALL SET /a filepath!x!="C:\TEST\%%a"
    )
)
echo %filepath1%
echo %filepath2%
pause
goto EOF

When I run the program, it seems to perform the FOR loop fine, but for filepath1 it displays just 0 and it does not display anything for filepath2. I belive the problem is in the if !X! == 1 and setting the filepath!x!. If I change anything to do with the !x!, it breaks the loop. What can I do to set the variables correctly and limit the loop to perform action on only 10 files?

4

1 に答える 1

1

あなたの元のコードには、そのときは意味をなさない(または少なくとも必要ではない)ものがいくつか含まれているため、あなたの質問が正しいかどうかはよくわかりません:-)

  • 「delims=|」あなたが使用したオプションはあなたのケースでは何もしていません
  • /aオプションが算術演算に使用されている場合(を参照) 、ラインhelp setで使用されている場合は間違っていますset filepath!x!...

とにかく、以下が機能するはずです:

setlocal ENABLEDELAYEDEXPANSION
cd C:\Test
FOR /f %%a IN ('dir /b') DO (
    SET /a x = !x! +1
    SET filepath!x!="C:\TEST\%%a"

    if !x! equ 10 goto done
)
:done
rem filepath1 to filepath10 are defined now, given there were up to 10 matching
rem files in the first place.

echo %filepath1%
echo %filepath2%

pause

file1.tif上記のコードはエラーチェックを行わず、問題のファイルが実際に呼び出されていることを確認しませんfile10.tif。あなたの質問(およびサンプルコード)から、それがあなたのケースで本当に必要かどうかははっきりしていません。上記のコードを改善できるように、それを明確にすることをお勧めします。

于 2012-09-12T05:16:31.120 に答える