13

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

"-String"

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

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

-String

我试过这个:

set currentParameter="-String"
echo %currentParameter:~1,-1%

这会按原样打印出字符串:

-String

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

set currentParameter="-String"
set currentParameter=%currentParameter:~1,-1%
echo %currentParameter%

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


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

set currentParameter="-String"
set currentParameter=%currentParameter:~1,-1%
echo %currentParameter%

它打印出来:

-String

但实际上我的批次有点复杂,在那里它不起作用。我将展示我编程的内容:

@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

输出是:

.
String WITHOUT stripping characters: "-String"
String WITH stripping characters:
.
.
String WITHOUT stripping characters: "-String2"
String WITH stripping characters: ~1,-1
.

但我想要的是:

.
String WITHOUT stripping characters: "-String"
String WITH stripping characters: -String
.
.
String WITHOUT stripping characters: "-String2"
String WITH stripping characters: -String2
.
4

4 回答 4

7

希望这会帮助你。

    setlocal enabledelayedexpansion
    
    echo String WITHOUT stripping characters: %%I 
    set currentParameter=%%I
    set currentParameter=!currentParameter:~1,-1!
    echo String WITH stripping characters: !currentParameter! 
于 2014-03-07T04:54:54.810 回答
4

您正在修改带括号的块内的变量。注意 - 新值不会在同一个块中使用(除非你用 ! 而不是 % 来分隔变量 - 并在 enabledelayedexpansion 模式下运行)。或者只是将几行提取到另一个子函数中,使用插入 ( ) 的普通行序列

问候,斯塔奇

于 2013-07-09T10:46:09.387 回答
3

此脚本利用 ENABLEDELAYEDEXPANSION。如果您不知道,批处理脚本执行 for 和 if 命令全部合二为一;因此,如果你这样做:

if true==true (
@echo off
set testvalue=123
echo %testvalue%
pause >NUL
)

您不会输出任何内容,因为执行 echo %testvalue% 时,它还没有识别出 testvalue 已更改。使用delayedexapnsion 允许脚本像现在一样读取该值,而忘记我之前提到的问题。你可以像 %testvalue% 一样使用它,但你可以使用 !testvalue! 解决这个问题:

if true==true (
@echo off
set testvalue=123
echo !testvalue!
pause >NUL
)
  • 会回显 123。

@echo off
SETLOCAL ENABLEDELAYEDEXPANSION
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

〜亚历克斯

于 2016-01-02T21:23:03.520 回答
0

我有类似的问题,但它通过删除 Ex 之间的空格来解决: set FileName=%Name:~0,11% # Working as No space before and after '=' Ex : set FileName = %Name:~0,11% # Not在“=”之前或之后作为空格工作

所以请尝试删除空格,它应该可以工作注意:应该重新打开命令行以刷新背景值,否则它会显示与存储在 temp 中相同的输出

于 2019-07-22T13:41:57.657 回答