Search code examples
stringbatch-filesplitdelimiter

Batch script - split by two or more spaces


I have a large string that looks like this

aa bb c d  f eeeee    ffff

I am not sure of the number of spaces that would come along with the string. The next time, string might have five spaces between aa and bb ansd so on...

aa     bb     c      f       eee ff

Is there a way I can split on two or more spaces (variable number of spaces) using delims in batch script?I always want the second token no matter how any spaces are there between first and second tokens.

PS : Edit I want the second token (by token I mean the token obtained after splitting by exactly two or more spaces). My token itself can contain a single space. Example: a b c d. In this want to extract b. Another example: a b b c d . In this I want to extract b b.


Solution

  • (Collected from various comments: Tokens are delimited by two or more spaces; You need the second token; Every token may or may not have single spaces)

    I commented every step and added an echo to show progress.

    @echo off
    setlocal 
    set "string=ads ads      d b c    dsad   ds   ads"
    echo 1: "%string%"
    REM remove first token (delimited by ecactly two spaces):
    set "string=%string:*  =%"
    echo 2: "%string%"
    REM remove leading spaces:
    for /f "tokens=*" %%a in ("%string%") do set "string=%%a"
    echo 3: "%string%"
    REM remove third and next tokens (delimited by two or more spaces)
    set string=%string:  =&REM %
    echo 4: "%string%"
    

    Only change to my answer to your previous question is the for to remove leading spaces