我通常喜歡自己嘗試解決這些問題,但目前我不得不承認我不知道從哪里開始。希望至少有人能引導我朝著正確的方向前進。
我有一個包含許多 .txt 檔案的檔案夾
Text1.txt
Text2.txt
Text3.txt
在我的 Windows bat 檔案中,我需要列出所述檔案夾的內容并將它們設定為要設定為變數的選項。例子:
cls
echo[
echo[ Please select an option
echo[
echo (1) Text1
echo (2) Text2
echo (3) Text3
echo[
set /p option=Type your selection (1-3) and press ENTER=
if !option!==1 set var=Text1
if !option!==2 set var=Text2
if !option!==3 set var=Text3
非常感謝任何建議,這個論壇很棒。
*在這里編輯是我嘗試過的
cls
echo[
echo[ Please select an option
echo[
dir /b "*.txt"
echo[
set /p option=Type your selection (1-3) and press ENTER=
if !option!==1 set var=text1
if !option!==2 set var=text2
if !option!==3 set var=text3
它可以作業,但不會在選項之前添加數字(1),并且它還使它們左對齊而不是居中。
Please select an option
text1.txt
text2.txt
text3.txt
Type your selection (1-3) and press ENTER=
uj5u.com熱心網友回復:
您可以構建不同的解決方案,這里有 2 個示例。
如果您只有幾個檔案可以使用choice:
@echo off
setlocal enabledelayedexpansion
for /F "tokens=1,*delims=[]" %%i in ('dir /b /a:-d *.txt ^| find /v /n ""') do (
echo %%i. %%j
set "cnt=!cnt!%%i"
set "fchoice%%i=%%~j"
)
choice /c %cnt% /m "Choose"
echo you chose !fchoice%errorlevel%!
如果您有很多檔案,choice可能不是一個可行的選擇,然后恢復為set /p:
@echo off
setlocal enabledelayedexpansion
for /F "tokens=1,*delims=[]" %%i in ('dir /b /a:-d *.txt ^| find /v /n ""') do (
echo %%i. %%j
set "cnt=!cnt!%%i"
set "fchoice%%i=%%~j"
)
set /p "chosen=Select a file by number: "
echo you chose !fchoice%chosen%!
uj5u.com熱心網友回復:
好吧,如果這是任何其他語言,你會怎么做?可能用您的目錄串列填充一個陣列,對吧?然后使用該陣列將選單選項與檔案選擇配對?好吧,不要讓 Batch 語言沒有陣列這一事實阻止你。它們很容易模擬。
@echo off & setlocal
set file.length=0
for %%I in (*.txt) do (
setlocal enabledelayedexpansion
for /f %%# in ("!file.length!") do endlocal & set "file[%%~#]=%%~I"
set /a file.ubound = file.length, file.length = 1
)
set file
你去吧。最后一行應該顯示所有以 開頭的變數的串列file,包括模擬.length和.ubound屬性。從那里,只需使用 afor /L %%I in (0, 1, %file.ubound%)來顯示您的選單。希望這會讓你開始。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/460718.html
