ファイルではなく、メモリ内の値の「リスト」が必要であると仮定します。
ほとんどの人は、インデックス値を介してアクセスできる値の「配列」を好むと思います。(注-バッチには正式な配列はありませんが、エミュレートできます)。
次の単純なコードは、ホームパスにが含まれていない限り、うまく機能します!
。が含まれていて遅延拡張が有効になっている場合、の拡張は%%B
破損します。!
@echo off
setlocal enableDelayedExpansion
:: Read the file and create an "array" of home paths
:: This will fail if any of the paths contain !
set /a cnt=0
for /f "usebackq tokens=2*" %%A in ("file.txt") do (
set /a cnt+=1
set "home.!cnt!=%%B"
)
:: Access the "array" members
for /l %%N in (1 1 %cnt%) do echo !home.%%N!
多くの環境で上記のコードを何年も実行しても、問題が発生することはありません。しかし、どこかの誰かが!
Oracleホームパスに含まれている可能性があります。に対処するために上記を修正するためのいくつかの戦略があります!
。以下は3つのオプションです。
オプション1-コードの量は最小ですが、CALLのために最も遅くなります
@echo off
setlocal disableDelayedExpansion
:: Read the file and create an "array" of home paths
:: This will safely process all paths, regardless of value
set /a cnt=0
for /f "usebackq tokens=2*" %%A in ("file.txt") do (
set /a cnt+=1
call set "home.%%cnt%%=%%B"
)
:: Access the "array"
setlocal enableDelayedExpansion
for /l %%N in (1 1 %cnt%) do echo !home.%%N!
オプション2-FINDSTRを使用して行をカウントする興味深い効率的な方法。
@echo off
setlocal disableDelayedExpansion
:: Read the file and create an "array" of home paths
:: This will safely process all paths, regardless of value
set /a cnt=0
for /f "tokens=1,3* delims=: " %%A in ('findstr /n "^" "file.txt"') do (
set "home.%%A=%%C"
set "cnt=%%A"
)
:: Access the "array" members
setlocal enableDelayedExpansion
for /l %%N in (1 1 %cnt%) do echo !home.%%N!
オプション3-遅延拡張トグルを使用する効率的な方法ですが、ほとんどのコード
@echo off
setlocal disableDelayedExpansion
:: Read the file and create an "array" of home paths
:: This will safely process all paths, regardless of value
set /a cnt=0
for /f "usebackq tokens=2*" %%A in ("file.txt") do (
set /a cnt+=1
setlocal enableDelayedExpansion
for %%N in (!cnt!) do (
endlocal
set "home.%%N=%%B"
)
)
:: Access the "array"
setlocal enableDelayedExpansion
for /l %%N in (1 1 %cnt%) do echo !home.%%N!
単一の変数にホームパスのリストを含めることもできます。各パスは引用符で囲む必要があります。パスは、スペース、コンマ、セミコロン、等号、またはタブで区切ることができます。スペースを選びました。
バッチ環境変数の最大サイズは約8191バイトであるため、リストのサイズは制限されています。このソリューションも、CALLのために比較的低速です。これらの問題はどちらも、現実の世界では問題になる可能性はありません。
@echo off
setlocal disableDelayedExpansion
:: Read the file and create a space delimited list of quoted home paths
:: This will safely process all paths, regardless of value
for /f "usebackq tokens=2*" %%A in ("file.txt") do (call set list=%%list%% "%%~B")
:: optional - remove leading space
(set list=%list:~1%)
:: Display the list
echo list=%list%
:: Access the list members
for %%F in (%list%) do echo %%~F