如何在CMD / Batch

时间:2017-08-18 12:37:47

标签: windows batch-file for-loop cmd delimiter

我希望将数字拆分为各自的数字,并使用Windows上的cmd / batch将它们存储到变量中。例如,数字' 38'应存储为' 3'在VAR1和' 8'在VAR2。

这是我目前对此问题的看法:

@echo off
SET NUMBER=38
FOR /F "TOKENS=1,2 delims=0123456789" %%A IN ("%NUMBER%") DO (CALL :VARSET %%A %%B)
ECHO %NUMBER% has the fallowing digits:
ECHO 1st digit: %VAR1%
ECHO 2nd digit: %VAR2%
PAUSE
EXIT /B 0

:VARSET
set VAR1=%1
set VAR2=%2
GOTO:EOF

我希望输出为:

ECHO 38 has the fallowing digits:
ECHO 1st digit: 3
ECHO 2nd digit: 8

但我明白了:

ECHO 38 has the fallowing digits:
ECHO 1st digit: Echo is off.
ECHO 2nd digit: Echo is off.

问题似乎是我使用' 0123456789'作为我的分隔符。也许这根本不可行使用FOR-LOOP?

编辑:错别字

4 个答案:

答案 0 :(得分:2)

用简单的数学做 - 我建议你从最低有效数字开始,以便能够轻松地重建数值。

@Echo off&SetLocal EnableExtensions EnableDelayedExpansion
:Again
set "#=" & Set Place=0
Set /p "#=Enter # :"
if "%#%" equ "" goto :Eof
Set /A Test=#
:Loop
Set /A "Place+=1,#[!Place!]=Test %% 10,Test/=10"
If "%Test%" gtr "0" goto :Loop
Set #
Echo =====
For /f "delims==" %%A in ('Set #') Do set "%%A="
Goto :Again

示例运行:

Enter # :123456789
#=123456789
#[0]=9
#[1]=8
#[2]=7
#[3]=6
#[4]=5
#[5]=4
#[6]=3
#[7]=2
#[8]=1
=====
Enter # :

答案 1 :(得分:2)

更简单,更快捷。只需在for /L命令中输入最大位数:

@echo off
setlocal EnableDelayedExpansion

set NUMBER=%1
echo %NUMBER% has the following digits:

for /L %%i in (1,1,12) do if defined NUMBER (
   set "VAR[%%i]=!NUMBER:~0,1!"
   set "NUMBER=!NUMBER:~1!"
)

set VAR[

答案 2 :(得分:0)

编辑:在我发布之前没有看到LotPings的回答。谢谢你的答案,也是如此。

@Jeff Zeitlin的链接和aschipfl的'课程':) 一个非常简单的解决方案是:

@echo off
SET NUMBER=38
SET VAR1=%NUMBER:~0,1%
SET VAR2=%NUMBER:~1,2%
ECHO %NUMBER% has the following digits:
ECHO 1st digit: %VAR1%
ECHO 2nd digit: %VAR2%
PAUSE
EXIT /B 0

也许更可重用的approch将是:

@ECHO OFF
SET COUNT=0
SET NUMBER=1234567890
CALL :SPLITNUM %NUMBER%
PAUSE
EXIT /b 0

:SPLITNUM
SETLOCAL ENABLEDELAYEDEXPANSION
SET NUMBER=%1
:LOOP
SET /A COUNT+=1
SET VAR%COUNT%=%NUMBER:~0,1%
ECHO VAR%COUNT% is !VAR%COUNT%!
SET NUMBER=%NUMBER:~1%
IF NOT "%NUMBER%"=="" (GOTO:LOOP)
ENDLOCAL
GOTO:EOF

答案 3 :(得分:0)

只是为了它的地狱:

@Echo Off
SetLocal EnableDelayedExpansion
Set "i=0"
For /F Delims^=^ EOL^= %%A In ('"CMD/U/CEcho %*|Find /V """') Do (Set/A i+=1
    Set "Var[!i!]=%%A")
Set Var[
Timeout -1

只需将其作为file.cmd 5678运行,其中file.cmd是此脚本的已保存名称,5678是一个字母数字字符串,可以拆分为单个变量。