Search code examples
for-loopbatch-filewindows-xpenumerate

Enumerating the delims of a FOR /F statement


I have a FOR /F statement which I want it to enumerate the delims the command is parsing. For example:

FOR /F "delims=," %%A IN ("This,is,a,comma,delimited,sentence") DO (
    some command to enumerate delims
)
:OUT

I want it to account for each delimited item in that sentence. In this case it would output 6

EDIT: I know the long way would be to do a check on each one.. but I'm trying to avoid that method:

IF %%A == [] SET enum=0 && GOTO:OUT
IF %%B == [] SET enum=1 && GOTO:OUT

etc.


Solution

  • There is NO way to directly enumerate items in a FOR /F "delims=..." command. The usual way to do that is via a loop that count one item, eliminate it from the sentence and repeat while there was a counted item.

    However, depending on the specific delimiter and the rest of characters in the sentence, you may use a FOR command (with no /F option) that will REPEAT its code with each item separated BY THE STANDARD BATCH DELIMITERS, that are comma, semicolon and equal-sign, besides spaces. In your particular example:

    SET ENUM=0
    FOR %%A IN (This,is,a,comma,delimited,sentence) DO SET /A ENUM+=1
    

    directly count the number of comma-separated items. If the delimiter is a character other than comma, semicolon or equal-sign, a possible solution is a three steps method:

    1- Replace spaces, comma, semicolon and equal-sign for another know character(s).
    2- Replace the delimiter for any Batch standard delimiter (space, comma, etc).
    3- Use a simple FOR to directly enumerate the items.