1

したがって、このコードを実行すると:

@echo off
setlocal enabledelayedexpansion

set lstFolders= First Second 

set intCounter=0
for %%i in (!lstFolders!) do (
    set /a intCounter += 1
    set strFlder=%%i
    set strFolder!intCounter!=!strFlder!
    echo %%i
    echo !strFlder!
    echo !strFolder%intCounter%!
    echo !strFolder1!
    echo !strFolder2!
)

:End
pause
endlocal

これは次のようになります。

First
First
ECHO is off.
First
ECHO is off.
Second
Second
ECHO is off.
First
Second

: という形式で変数 create をエコーできないのはなぜ!strFolder%intCounter%!ですか? この変数を参照して、その中にあるデータを取得する別の方法はありますか?

4

2 に答える 2

1

@ mklement0 が既に述べたように、追加の評価ステップが必要です。
しかしecho "%%strFolder!intCounter!%%"、 を使用するにもかかわらず、遅延展開をお勧めします。
遅延拡張はどのコンテンツにも影響されないため、echo "%%strFolder...引用符や感嘆符を含むコンテンツでは失敗します。

@echo off
setlocal enabledelayedexpansion

set "lstFolders=First Second"

set intCounter=0
for %%i in (!lstFolders!) do (
    set /a intCounter+= 1
    set "strFlder=%%i"
    set "strFolder!intCounter!=!strFlder!"
    echo !strFlder!
    set "varname=strFolder!intCounter!"
    for /F "delims=" %%A in (""!varname!"") do echo Indirect %%~A=!%%~A!
)

引用符を二重にすることで、FOR/F ループの eol 文字の問題を回避できます。

于 2016-08-12T07:15:28.453 に答える
0

警告: 以下のコードは、次のリスト値 (%lstFolders%などのトークンFirst) でのみ機能します。

  • どちらのスペースも含まない
  • また、次の文字のいずれも:& | < > "

このようなケースを処理するには、別のループ アプローチが必要になります。

@echo off
setlocal enabledelayedexpansion

set "lstFolders=First Second" 

set intCounter=0
for %%i in (%lstFolders%) do (
      rem Increment the counter
    set /a intCounter += 1
      rem Echo the loop variable
    echo #!intCounter!=%%i
      rem Set variable strFolder<intCounter> to the loop variable's value
    set "strFolder!intCounter!=%%i"
      rem Echo the variable created using variable indirection with for /f ('...')
    for /f "delims=" %%v in ('echo "%%strFolder!intCounter!%%"') do set "thisFolder=%%~v"
    echo %%thisFolder%% ^(via %%strFolder!intCounter!%%^)=!thisFolder!
)

上記を実行すると、次のようになります。

#1=First
%thisFolder% (via %strFolder1%)=First
#2=Second
%thisFolder% (via %strFolder2%)=Second

あなたが探しているのは変数の間接化です:

  • 変数を間接的に (別の変数の値から動的に作成する名前によって)設定できますが、たとえば、
    • set "strFolder!intCounter!=%%i"の値を!intCounter!持つ ,変数を の値に1正しく設定します),strFolder1%%i
  • その方法では変数の値を取得できません。提供できる追加の評価ステップ必要です。for /f ... ('echo ...'):

    • for /f "delims=" %%v in ('echo "%%strFolder!intCounter!%%"') do ...コマンドの出力を一重引用符 ( ) で解析しecho ...、結果全体 ( delims=) を変数に割り当てます%%v
      (コマンドがシェルのメタ文字を正しく処理するために引数%%~vの周りに追加された二重引用符を削除します)。echo& | < >

    • %%strFolder!intCounter!%% これは、二重化されたインスタンスを囲むおかげで、最終的にはリテラルになります。これは、コマンドによって実行されたときにコマンドが見るものであり、変数参照を評価してその値に展開しstrFolder!intCounter!ますstrFolder1!intCounter!1 % %strFolder1%echofor

于 2016-08-12T03:16:04.333 に答える