windows - findstr命令变量在for循环批处理脚本中的路径中扩展(Windows,批处理脚本)

标签 windows batch-file cmd findstr

echo off
set "MasterFolder=C:\Users\Development\test_folder"
SetLocal EnableDelayedexpansion
@FOR /f "delims=" %%f IN ('dir /b /s "%MasterFolder%\*.txt"') DO (
    set /a "idx+=1"
    set "FileName[!idx!]=%%~nxf"
    set "FilePath[!idx!]=%%~dpFf"
)

for /L %%i in (1,1,%idx%) do (
    echo [%%i] "!FileName[%%i]!"

    set "loc=%MasterFolder%\!FileName[%%i]!"
    echo path: %MasterFolder%\!FileName[%%i]!
    echo loc: !loc!
    FOR /F "tokens=1,2 delims=:" %%1 in ('findstr /o "^" "%MasterFolder%\test_1.txt"') DO (
        set new_pos=%%1
        echo new_pos !new_pos!
    )
)

上面的代码可以工作,但是下面的代码不起作用。

echo off
... 
FOR /F "tokens=1,2 delims=:" %%1 in ('findstr /o "^" "%MasterFolder%\!FileName[%%i]!"') DO (
        set new_pos=%%1
        echo new_pos !new_pos!
    )
)
echo off
...
    FOR /F "tokens=1,2 delims=:" %%1 in ('findstr /o "^" "!loc!"') DO (
        set new_pos=%%1
        echo new_pos !new_pos!
    )
)

我所做的就是将 test_1.txt 替换为 !FileName[%%i]!,或者使用新变量并将全部替换为 "!loc!"

但是最后两个代码不起作用,我需要这种方式,因为它通过第一个 for 循环自动获取文件夹中的文件名。

我猜想 findstr 或变量扩展顺序有错误,但我很难弄清楚。

最佳答案

很明显!

使用 !file... 时,在行中引入感叹号。

这会触发phase 5 (delayed epxansion phase) of the parser .
在该阶段,变量被扩展并且插入符用于转义下一个字符,独立于它们所在的位置(带引号或不带引号)!

因此,您的搜索字符串 "^" 将转换为 ""

只需将插入符号加倍即可 findstr/o "^^"!File...

感叹号效果有点出乎意料

setlocal EnableDelayedExpansion
echo One Caret "^"
echo One Caret "^" and a bang ^^!

输出

One Caret "^"
One Caret "" and a bang !

关于windows - findstr命令变量在for循环批处理脚本中的路径中扩展(Windows,批处理脚本),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60526640/

相关文章:

C++:将 __int64 转换为 unsigned long

windows - 使用 cmd 提示符编写脚本

windows - 7-Zip 关闭匹配 *.* 的文件夹的递归

windows - 防止窗口被拖过屏幕边缘

batch-file - 批处理 IF ELSE 语句都执行

windows - 在命令行输出中搜索字符串

java - 奇怪的 CMD 环境变量行为

powershell - Windows在创建文件之前先获取文件的短路径

cmd - 自动生成 makecert 密码

Python 多处理不断生成 pythonw.exe 进程而不做任何实际工作