English 中文(简体)
How to split a string by spaces in a Windows batch file?
原标题:

Suppose I have a string "AAA BBB CCC DDD EEE FFF".

How can I split the string and retrieve the nth substring, in a batch file?

The equivalent in C# would be

"AAA BBB CCC DDD EEE FFF".Split()[n]
最佳回答

see HELP FOR and see the examples

or quick try this

 for /F %%a in ("AAA BBB CCC DDD EEE FFF") do echo %%a
问题回答

Three possible solutions to iterate through the words of the string:

Version 1:

@echo off & setlocal
set s=AAA BBB CCC DDD EEE FFF
for %%a in (%s%) do echo %%a

Version 2:

@echo off & setlocal
set s=AAA BBB CCC DDD EEE FFF
set t=%s%
:loop
for /f "tokens=1*" %%a in ("%t%") do (
   echo %%a
   set t=%%b
   )
if defined t goto :loop

Version 3:

@echo off & setlocal
set s=AAA BBB CCC DDD EEE FFF
call :sub1 %s%
exit /b
:sub1
if "%1"=="" exit /b
echo %1
shift
goto :sub1

Version 1 does not work when the string contains wildcard characters like * or ? .

Versions 1 and 3 treat characters like = , ; or , as word separators. These characters have the same effect as the space character.

This is the only code that worked for me:

for /f "tokens=4" %%G IN ("aaa bbb ccc ddd eee fff") DO echo %%G 

output:

ddd

The following code will split a string with an arbitrary number of substrings:

@echo off
setlocal ENABLEDELAYEDEXPANSION

REM Set a string with an arbitrary number of substrings separated by semi colons
set teststring=The;rain;in;spain

REM Do something with each substring
:stringLOOP
    REM Stop when the string is empty
    if "!teststring!" EQU "" goto END

    for /f "delims=;" %%a in ("!teststring!") do set substring=%%a

        REM Do something with the substring - 
        REM we just echo it for the purposes of demo
        echo !substring!

REM Now strip off the leading substring
:striploop
    set stripchar=!teststring:~0,1!
    set teststring=!teststring:~1!

    if "!teststring!" EQU "" goto stringloop

    if "!stripchar!" NEQ ";" goto striploop

    goto stringloop
)

:END
endlocal

If someone need to split a string with any delimiter and store values in separate variables, here is the script I built,

FOR /F "tokens=1,2 delims=x" %i in ("1920x1080") do (
  set w=%i
  set h=%j
)
echo %w%
echo %h%

Explanation: tokens defines what elements you need to pass to the body of FOR, with token delimited by character x . So after delimiting, the first and second token are passed to the body. In the body %i refers to first token and %j refers to second token. We can take %k to refer to 3rd token and so on..

Please also type HELP FOR in cmd to get a detailed explanation.

easy

batch file:

FOR %%A IN (1 2 3) DO ECHO %%A

command line:

FOR %A IN (1 2 3) DO ECHO %A

output:

1
2
3

I ended up with the following:

set input=AAA BBB CCC DDD EEE FFF
set nth=4
for /F "tokens=%nth% delims= " %%a in ("%input%") do set nthstring=%%a
echo %nthstring%

With this you can parameterize the input and index. Make sure to put this code in a bat file.

The following code will split a string with N number of substrings with # separated values. You can use any delimiter

@echo off
if "%1" == "" goto error1

set _myvar="%1"

:FORLOOP
For /F "tokens=1* delims=#" %%A IN (%_myvar%) DO (
    echo %%A
    set _myvar="%%B"
    if NOT "%_myvar%"=="" goto FORLOOP
)

goto endofprogram
:error1
echo You must provide Argument with # separated

goto endofprogram
:endofprogram

or Powershell for a 0 indexed array.

PS C:> "AAA BBB CCC DDD EEE FFF".Split()
AAA
BBB
CCC
DDD
EEE
FFF

PS C:> ("AAA BBB CCC DDD EEE FFF".Split())[0]
AAA
set a=AAA BBB CCC DDD EEE FFF
set a=%a:~6,1%

This code finds the 5th character in the string. If I wanted to find the 9th string, I would replace the 6 with 10 (add one).

@echo off

:: read a file line by line
for /F  %%i in ( type data.csv ) do (
    echo %%i
    :: and we extract four tokens, ; is the delimiter.
    for /f "tokens=1,2,3,4 delims=;" %%a in ("%%i") do (
        set first=%%a&set second=%%b&set third=%%c&set fourth=%%d
        echo %first% and %second% and %third% and %fourth% 
    )
)

Here is a solution based on a "function" which processes each character until it finds the delimiter character.

It is relatively slow, but it is at least not a brain teaser (except for the function part).

:: Example #1:
set data=aa bb cc
echo Splitting off from "%data%":
call :split_once "%data%" " " "left" "right"
echo Split off: %left%
echo Remaining: %right%
echo.

:: Example #2:
echo List of paths in PATH env var:
set paths=%PATH%
:loop
    call :split_once "%paths%" ";" "left" "paths"
    if "%left%" equ "" goto loop_end
    echo %left%
goto loop
:loop_end



:: HERE BE FUNCTIONS
goto :eof

:: USAGE:
::   call :split_once "string to split once" "delimiter_char" "left_var" "right_var"
:split_once
    setlocal
    set right=%~1
    set delimiter_char=%~2
    set left=

    if "%right%" equ "" goto split_once_done

    :split_once_loop
        if "%right:~0,1%" equ "%delimiter_char%" set right=%right:~1%&& goto split_once_done
        if "%right:~0,1%" neq "%delimiter_char%" set left=%left%%right:~0,1%
        if "%right:~0,1%" neq "%delimiter_char%" set right=%right:~1%
        if "%right%" equ "" goto split_once_done
    goto split_once_loop

    :split_once_done
    endlocal & set %~3=%left%& set %~4=%right%
goto:eof

you can use vbscript instead of batch(cmd.exe)

Set objFS = CreateObject("Scripting.FileSystemObject")
Set objArgs = WScript.Arguments
str1 = objArgs(0)
s=Split(str1," ")
For i=LBound(s) To UBound(s)
    WScript.Echo s(i)
    WScript.Echo s(9)   get the 10th element
Next

usage:

c:	est> cscript /nologo test.vbs "AAA BBB CCC"

UPDATE: Well, initially I posted the solution to a more difficult problem, to get a complete split of any string with any delimiter (just changing delims). I read more the accepted solutions than what the OP wanted, sorry. I think this time I comply with the original requirements:

 @echo off
 IF [%1] EQU [] echo get n ["user_string"] & goto :eof
 set token=%1
 set /a "token+=1"
 set string=
 IF [%2] NEQ [] set string=%2
 IF [%2] EQU [] set string="AAA BBB CCC DDD EEE FFF"
 FOR /F "tokens=%TOKEN%" %%G IN (%string%) DO echo %%~G

An other version with a better user interface:

 @echo off
 IF [%1] EQU [] echo USAGE: get ["user_string"] n & goto :eof
 IF [%2] NEQ [] set string=%1 & set token=%2 & goto update_token
 set string="AAA BBB CCC DDD EEE FFF"
 set token=%1
 :update_token
 set /a "token+=1"
 FOR /F "tokens=%TOKEN%" %%G IN (%string%) DO echo %%~G

Output examples:

E:utilsat>get
USAGE: get ["user_string"] n
E:utilsat>get 5
FFF
E:utilsat>get 6
E:utilsat>get "Hello World" 1
World

This is a batch file to split the directories of the path:

@echo off
set string="%PATH%"
:loop
FOR /F "tokens=1* delims=;" %%G IN (%string%) DO (
    for /f "tokens=*" %%g in ("%%G") do echo %%g
    set string="%%H"
    )
if %string% NEQ "" goto :loop

2nd version:

@echo off
set string="%PATH%"
:loop 
FOR /F "tokens=1* delims=;" %%G IN (%string%) DO set line="%%G" & echo %line:"=% & set string="%%H"
if %string% NEQ "" goto :loop

3rd version:

@echo off
set string="%PATH%"
:loop
FOR /F "tokens=1* delims=;" %%G IN (%string%) DO CALL :sub "%%G" "%%H"
if %string% NEQ "" goto :loop
goto :eof

:sub
set line=%1
echo %line:"=%
set string=%2

This works for me (just an extract from my whole script)

choice /C 1234567H /M "Select an option or ctrl+C to cancel"
set _dpi=%ERRORLEVEL%

if "%_dpi%" == "8" call :helpme && goto menu 

for /F "tokens=%_dpi%,*" %%1 in ("032 060 064 096 0C8 0FA 12C") do set _dpi=%%1
echo _dpi:%_dpi%:

one more variation - this looks for the program "cmd.exe" in the current path and reports the first match:

@echo off
setlocal
setlocal enableextensions
setlocal enabledelayedexpansion

set P=%PATH%
:pathloop
for /F "delims=; tokens=1*" %%f in ("!P!") do (
    set F=%%f
    if exist %%fcmd.exe goto found
    set P=%%g
)
if defined P goto pathloop

echo path of cmd.exe was not found!
goto end

:found
echo found cmd.exe at %F%
goto end

:end




相关问题
Why running a service as Local System is bad on windows?

I am trying to find out the difference between difference service account types. I tumbled upon this question. The answer was because it has powerful access to local resources, and Network Service ...

Programmatically detect Windows cluster configuration?

Does anyone know how to programatically detect that a Windows server is part of a cluster? Further, is it possible to detect that the server is the active or passive node? [Edit] And detect it from ...

get file icon for Outlook appointment (.msg)

I ve read Get File Icon used by Shell and the other similar posts - and already use SHFileInfo to get the associated icon for any given extension, and that works great. However, Outlook uses ".msg" ...

Identifying idle state on a windows machine

I know about the GetLastInputInfo method but that would only give me the duration since last user input - keyboard or mouse. If a user input was last received 10 minutes ago, that wouldn t mean the ...

Terminating a thread gracefully not using TerminateThread()

My application creates a thread and that runs in the background all the time. I can only terminate the thread manually, not from within the thread callback function. At the moment I am using ...

热门标签