Advertisement
Advertisement


How to split a string by spaces in a Windows batch file?


Question

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]
2018/02/01
1
58
2/1/2018 9:11:01 AM

Accepted Answer

see HELP FOR and see the examples

or quick try this

 for /F %%a in ("AAA BBB CCC DDD EEE FFF") do echo %%c
2018/04/20
32
4/20/2018 3:18:45 PM


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
2012/11/15

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
2011/10/12

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
2010/11/10

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
2013/07/31

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.

2019/04/25

Source: https://stackoverflow.com/questions/1707058
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]