Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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] 
like image 896
Cheeso Avatar asked Nov 10 '09 10:11

Cheeso


People also ask

What is %% in a batch file?

Use double percent signs ( %% ) to carry out the for command within a batch file. Variables are case sensitive, and they must be represented with an alphabetical value such as %a, %b, or %c. ( <set> ) Required. Specifies one or more files, directories, or text strings, or a range of values on which to run the command.

How do you split a string into characters?

Split(Char, Int32, StringSplitOptions) Splits a string into a maximum number of substrings based on a specified delimiting character and, optionally, options. Splits a string into a maximum number of substrings based on the provided character separator, optionally omitting empty substrings from the result.

What is == in batch?

[ == ] (Double Equals) The "IF" command uses this to test if two strings are equal: IF "%1" == "" GOTO HELP. means that if the first parameter on the command line after the batch file name is equal to nothing, that is, if a first parameter is not given, the batch file is to go to the HELP label.

Can a batch file read a text file?

Reading of files in a Batch Script is done via using the FOR loop command to go through each line which is defined in the file that needs to be read. Since there is a no direct command to read text from a file into a variable, the 'for' loop needs to be used to serve this purpose.


1 Answers

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.

like image 129
Christian d'Heureuse Avatar answered Sep 21 '22 13:09

Christian d'Heureuse