【问题标题】:how do I assign multiple findstr results to separate variables如何将多个 findstr 结果分配给单独的变量
【发布时间】:2015-08-11 11:52:58
【问题描述】:

我正在尝试通过使用批处理文件将 CHDIR 结果保存到临时文本文档中,使用 FOR 将子目录名称分配给变量

批处理文件输入:

CD /d 路径名
目录 /b /d >temp.txt
FINDSTR /b /n 字符串路径名\temp.txt
ECHO 查找上面的字符串结果
暂停
FOR /F "tokens=1-3" %%A IN ('FINDSTR /b string pathname\temp.txt') DO (
SET One=%%A
SET 2=%%B
设置三=%%C )
回声 %One%
回声 %Two%
ECHO %3%
暂停

命令提示符输出:

目录1
目录2
目录3
在上面查找字符串结果
按任意键继续 。 . .
目录3
回声已关闭。
回声已关闭。
按任意键继续 。 . .

如果正确分配了 ECHO 变量,则初始 FINDSTR 的结果应与 ECHO 变量匹配,但仅捕获最终子目录名称且未分配最后两个变量。

如何让每个子目录分配给单独的变量? 有没有更简单的方法来实现这个目标?

【问题讨论】:

    标签: batch-file


    【解决方案1】:

    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%
    

    【讨论】:

    • 非常感谢,我对脚本还是很陌生(显然)。我想我试图逆向工程的 .bat 只是混淆了这个问题。
    【解决方案2】:

    存储和处理未定义数量的项目的常用方法是通过数组,它是一个名称相同的变量,但有几个元素通过数字索引或用正方形括起来的下标选择括号;例如: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%,它将在 for 迭代之前扩展一次。如果变量以这种方式包含在百分比中:!index! 并启用延迟扩展(通过开头的setlocal 命令),index 的值将在每次行执行时扩展。您可以在批处理文件here 中阅读有关阵列管理的进一步说明。

    【讨论】:

    • 感谢您提供的信息!我也得试试这个方法。
    猜你喜欢
    • 1970-01-01
    • 2020-12-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-22
    • 1970-01-01
    • 1970-01-01
    • 2021-02-04
    • 1970-01-01
    相关资源
    最近更新 更多