如何优化我的批处理脚本代码

时间:2017-01-17 12:09:53

标签: batch-file

您好我想将以下批处理脚本优化为单行代码。我试过多种方法但无法做到。你可以帮我在这里优化下面的代码。

IF "%EnvName%"=="UT" (SET EnvName=UT)
IF "%EnvName%"=="UT1" (SET EnvName=UT)
IF "%EnvName%"=="UT2" (SET EnvName=UT)
IF "%EnvName%"=="ST" (SET EnvName=ST)
IF "%EnvName%"=="ST1" (SET EnvName=ST)
IF "%EnvName%"=="ST2" (SET EnvName=ST)
IF "%EnvName%"=="ST3" (SET EnvName=ST)
IF "%EnvName%"=="SIT" (SET EnvName=SIT)
IF "%EnvName%"=="SIT1" (SET EnvName=SIT)
IF "%EnvName%"=="SIT2" (SET EnvName=SIT) 
IF "%EnvName%"=="SIT3" (SET EnvName=SIT)
IF "%EnvName%"=="SIT4" (SET EnvName=SIT)
IF "%EnvName%"=="UAT" (SET EnvName=UAT) 
IF "%EnvName%"=="UAT1" (SET EnvName=UAT) 
IF "%EnvName%"=="UAT2" (SET EnvName=UAT) 
IF "%EnvName%"=="UAT3" (SET EnvName=UAT)
IF "%EnvName%"=="UAT4" (SET EnvName=UAT)
IF "%EnvName%"=="SND" (SET EnvName=SND) 
IF "%EnvName%"=="SND1" (SET EnvName=SND) 
IF "%EnvName%"=="SND2" (SET EnvName=SND) 
IF "%EnvName%"=="SND3" (SET EnvName=SND)
IF "%EnvName%"=="SND4" (SET EnvName=SND)
IF "%EnvName%"=="DEVL" (SET EnvName=DEVL)
IF "%EnvName%"=="DM" (SET EnvName=DM)

2 个答案:

答案 0 :(得分:2)

@echo off
REM EnvName gets set somewhere here
set "numbers=1 2 3 4 5 6 7 8 9 0"
for %%a in (%numbers%) do (
  if "%EnvName:~-1%"=="%%a" (
    set "EnvName=%EnvName:~0,-1%"
    goto :nextStep
  )
)
:nextStep
echo %EnvName%

遍历所有数字并检查变量的最后一个字符是否等于其中一个。如果是这样,它将删除最后一个数字并转到下一步,在我的情况下,它只是回显变量。

%EnvName%=DLM3的示例 - > DLM

注意:如果不再是数字, 将删除最后一个字符!

答案 1 :(得分:0)

@echo off
setlocal EnableDelayedExpansion

rem Define the sets of valid names:
set "set[UT]=2, set[ST]=3, set[SIT]=4, set[UAT]=4, set[SND]=4, set[DEVL]=0, set[DM]=0" 

set "digits=123456789"


rem The Value:
set "EnvName=%1"


rem Separate parts
set "base=%EnvName:~0,-1%"
set "last=%EnvName:~-1%"

rem If last char is a digit
if "!digits:%last%=!" neq "%digits%" (

   rem Check the digit vs. max value
   if "%last%" leq "!set[%base%]!" set "EnvName=%base%"

) else (

   rem Check the value vs. defined sets
   if defined set[%EnvName%] set "EnvName=%EnvName%"

   rem Note that previous IF is meaningless, unless an ELSE is inserted here
   rem or a different variable is used for the result

)