首页 > 解决方案 > 从批处理文件中的变量中删除最后一个字符

问题描述

我试图通过批处理文件根据其他一些名为“choice”的变量的最后一个字符为名为“doNotLog”的变量分配一个值。

变量选择的结构是:

1) 具有 1 个或多个数字的整数

2) 或1位或多位整数加上最后一个字符“n”

目标是:

1) 如果 "choice" 的最后一个字符是 n,则将 "doNotLog" 的值设置为 true

2)最终从“选择”中删除 n

我用来实现这一点的批处理文件是:

@echo off

echo enter choice
set/p choice=
set doNotLog=false

setlocal ENABLEDELAYEDEXPANSION 
if %choice:~-1,1%==n ( 
    set doNotLog=true
    set choice=!choice:n=!
)
endlocal

echo After changes:
echo choice=  %choice%
echo donotLog=  %doNotLog%

@pause

它产生以下输出:

enter choice
54n
After changes:
choice=  54n
donotLog=  false
Press any key to continue . . .

但是,我期待以下输出:

enter choice
54n
After changes:
choice=  54
donotLog=  true
Press any key to continue . . .

如何实现我想要的输出

标签: windowsbatch-filecmd

解决方案


变量扩展在Set命令的帮助信息下进行了描述。打开命令提示符窗口并输入set /?以阅读它。

这里有一些帮助示例:

C:\Users\Mohd>Set "Variable=String"

C:\Users\Mohd>Echo(%Variable%
String

C:\Users\Mohd>Echo(%Variable:~0,-1%
Strin

C:\Users\Mohd>Echo(%Variable:~0,1%
tring

C:\Users\Mohd>Echo(%Variable:~0,-2%
Stri

C:\Users\Mohd>Echo(%Variable:~-1,1%
g

C:\Users\Mohd>Echo(%Variable:~1,-1%
trin

C:\Users\Mohd>Echo(%Variable:~1,1%
t

C:\Users\Mohd>Echo(%Variable:~1,2%
tr

C:\Users\Mohd>Echo(%Variable:~1,-2%
tri

C:\Users\Mohd>Echo(%Variable:~2,1%
r

C:\Users\Mohd>Echo(%Variable:~2,-1%
rin

C:\Users\Mohd>Echo(%Variable:~2,-2%
ri

C:\Users\Mohd>Echo(%Variable:~-2,2%
ng

C:\Users\Mohd>Echo(%Variable:~-2,1%
n

C:\Users\Mohd>Echo(%Variable:~2,-1%
rin

推荐阅读