簡體   English   中英

如何將多個findstr結果分配給單獨的變量

[英]how do I assign multiple findstr results to separate variables

我試圖通過使用批處理文件將CHDIR結果保存到臨時文本文檔中,從而使用FOR為變量分配子目錄名稱

批處理文件輸入:

CD / d路徑名
DIR / b / d> temp.txt
FINDSTR / b / n字符串路徑名\\ temp.txt
回聲在上面找到字符串結果
暫停
FOR / F“令牌= 1-3” %% A IN('FINDSTR / b字符串pathname \\ temp.txt')DO(
SET One = %% A
第二組= %% B
設置三= %% C

回聲%One%
回聲%Two%
回聲%三%
暫停

命令提示符輸出:

目錄1
目錄2
目錄3
在上面找到字符串結果
按任意鍵繼續 。
目錄3
回音關閉。
回音關閉。
按任意鍵繼續 。

如果正確分配了初始FINDSTR的結果,則它們應與ECHO'd變量匹配,但僅捕獲最終的子目錄名稱,而未分配最后兩個變量。

如何將每個子目錄分配給一個單獨的變量? 有沒有更簡單的方法可以實現這一目標?

tokens子句用於拆分每條輸入行,而不是確定要讀取的行數。

@echo off
    setlocal enableextensions disabledelayedexpansion

    rem Clean variables
    for %%b in (one two three) do set "%%b="

    rem Read folders
    for /d %%a in ("c:\somewhere\*") do (
        rem For each folder found, assign to a non assigned variable
        set "done="
        for %%b in (one two three) do if not defined done if not defined %%b (
            set "%%b=%%a"
            set "done=1"
        )
    )

    echo %one%
    echo %two%
    echo %three%

存儲和處理數量不確定的項目的通常方法是通過一個數組 ,該數組是一個具有一個名稱的變量,但是有幾個元素是通過方括號內的數字索引或下標選擇的; 例如: set array[1]=Element number 1

@echo off
setlocal EnableDelayedExpansion

rem Initialize the index
set index=0

rem Process all folders
cd /D pathname
for /D %%a in (string*) do (
   rem Increment the index to next element
   set /A index+=1
   rem Store the folder in next array element
   set "folder[!index!]=%%a"
)

rem Store the total number of folders
set number=%index%

rem Show the first folder
echo First folder: %folder[1]%

rem Show the last folder
echo Last folder: !folder[%number%]!

rem Show all folders
for /L %%i in (1,1,%number%) do echo %%i- !folder[%%i]!

此方法需要延遲擴展,因為索引的值在for循環內更改。 如果以這種方式擴展%index%%index% ,則它將在for迭代之前僅擴展一次。 如果變量以這種方式用百分號括起來: !index! 並且啟用了延遲擴展(通過開始處的setlocal命令), 每次執行該行時都會擴展index的值。 您可以在此處在批處理文件中閱讀有關陣列管理的更多說明。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM