批处理文件 - 在 for 循环中替换通配符

batchfile - Wildcard in replace in for loop

我正在尝试获取文件中的两部分字符串。为此,我需要获取 -(space - space) 之前和之后的部分。我尝试使用此代码:

@echo off
SETLOCAL enabledelayedexpansion
for /F "tokens=*" %%A in (downloads.txt) do (
set str=%%A
echo !str!
set "string1=!str: - *=!"
set "string2=!str:* - =!"
echo "!string1!+!string2!"
)
pause

完整的输出应该是

someURL.com+some file.txt

然而,实际输出是:

"someURL.com - some file.txt+some file.txt"

所以我的第一个字符串的替换代码显然有问题。我认为这与通配符有关,因为这是唯一不同的部分。

downloads.txt 的内容如下所示:

someURL.com - some file.txt

编辑:

我使用 achipfl 的代码修复了它:

@echo off
SETLOCAL enabledelayedexpansion
for /F "tokens=*" %%A in (downloads.txt) do (
set str=%%A
set "strR=!str:* - =!"
for /F "delims=*" %%f in ("!strR!") do set "strL=!str: - %%f=!"
set "strL=!strL: - =!"
echo "!strL!+!strR!"
)
pause

你的问题是通配符只能作为要搜索的字符串的开头。

一个简单的非防弹解决方案(例如字符串中的 =!*& 个字符可能是个问题),您可以在获得字符串的右侧部分后将其删除以获得左侧部分

@echo off
SETLOCAL enabledelayedexpansion
    for /F "delims=" %%A in (downloads.txt) do (
        rem Get the full string
        set "str=%%A"
        echo !str!

        rem Get the right part of the string
        set "string2=!str:* - =!"

        rem Get the left part of the string just removing the right part
        for /f "delims=" %%B in ("!string2!") do set "string1=!str: - %%B=!"

        echo "[!string1!] [!string2!]"
        echo(

    )
    pause

假设-部分只出现一次,且整个字符串不以*开头,你可以这样做:

:SUB
set "strR=!str:* - =!"
set "strL=!str: - %strR%=!"
set "strL=!strL: - =!"

要在循环中使用它,您应该将它放在子例程中并通过 call :SUB 调用它,因为还使用了直接 % 变量扩展。

字符串不能包含=%!^,否则此方法失败。