从Windows批处理文件中的字符串中删除第一个和最后一个字符

Met*_*d89 10 windows character batch-file strip

我的Windows批处理文件中有以下字符串:

"-String"
Run Code Online (Sandbox Code Playgroud)

该字符串还包含字符串开头和结尾的两个引号,如上所述.

我想剥离第一个和最后一个字符,以便我得到以下字符串:

-String
Run Code Online (Sandbox Code Playgroud)

我试过这个:

set currentParameter="-String"
echo %currentParameter:~1,-1%
Run Code Online (Sandbox Code Playgroud)

这打印出应该是的字符串:

-String
Run Code Online (Sandbox Code Playgroud)

但是当我尝试像这样存储编辑过的字符串时,它会失败:

set currentParameter="-String"
set currentParameter=%currentParameter:~1,-1%
echo %currentParameter%
Run Code Online (Sandbox Code Playgroud)

什么都没打印出来.我做错了什么?


这真的很奇怪.当我删除这样的字符时,它可以工作:

set currentParameter="-String"
set currentParameter=%currentParameter:~1,-1%
echo %currentParameter%
Run Code Online (Sandbox Code Playgroud)

打印出来:

-String
Run Code Online (Sandbox Code Playgroud)

但实际上我的批次有点复杂,并且它不起作用.我将展示我编程的内容:

@echo off

set string="-String","-String2"

Set count=0
For %%j in (%string%) Do Set /A count+=1


FOR /L %%H IN (1,1,%COUNT%) DO ( 

    echo .
        call :myFunc %%H
)
exit /b

:myFunc
FOR /F "tokens=%1 delims=," %%I IN ("%string%") Do (

    echo String WITHOUT stripping characters: %%I 
    set currentParameter=%%I
    set currentParameter=%currentParameter:~1,-1%

    echo String WITH stripping characters: %currentParameter% 

    echo .

)
exit /b   

:end
Run Code Online (Sandbox Code Playgroud)

输出是:

.
String WITHOUT stripping characters: "-String"
String WITH stripping characters:
.
.
String WITHOUT stripping characters: "-String2"
String WITH stripping characters: ~1,-1
.
Run Code Online (Sandbox Code Playgroud)

但我想要的是:

.
String WITHOUT stripping characters: "-String"
String WITH stripping characters: -String
.
.
String WITHOUT stripping characters: "-String2"
String WITH stripping characters: -String2
.
Run Code Online (Sandbox Code Playgroud)

小智 6

希望能帮到你。不带剥离字符的回显字符串:%%I

set currentParameter=%%I
set currentParameter=!currentParameter:~1,-1!

echo String WITH stripping characters: !currentParameter! 

echo .
Run Code Online (Sandbox Code Playgroud)

它可能会起作用。试试这个。

  • 您可能应该提到,这仅在启用“延迟扩展”时才有效,这可能会产生一些其他难以调试的副作用。 (2认同)

小智 4

您正在修改括号内的变量。请注意 - 新值不会在同一个块中使用(除非您用 ! 而不是 % 分隔变量 - 并且在启用延迟扩展模式下运行)。或者只是使用由 ( ) 插入的简单行序列将这几行提取到另一个子函数中

问候,斯塔克