Search code examples
windowsbatch-filebatch-rename

windows batch script .bat for loop


I'm having a hard time understanding what the below code is doing.

for /f "delims=:. tokens=1-4" %%t in ("%TIME: =0%") do (
        set FILENAME=event-%5-%%t%%u%%v%%w
    )

I know it's a for loop.

/f => I imagine this means for each file in a directory.

delims=:. => I understand this means use : as a delimiter. Not sure what . means.

tokens=1-4 => It seems this is grabbing the first four files in a directory

%%t => Not sure what this means

("%TIME: =0%") => No idea what this means

So for each file matching the above criteria, it does this:

set FILENAME=event-%5-%%t%%u%%v%%w => Which i presume means rename each file.

What i also dont understand is:

event-%5-%%t%%u%%v%%w => I know "event" is part of the name. But what does %5-%%t%%u%%v%%w mean?


Solution

  • I know it's a for loop. correct

    /f => I imagine this means for each file in a directory. Not quite. /f is a kind of "multi-purpose switch" - see for /? for details

    delims=:. => I understand this means use : as a delimiter. Not sure what . means. it defines both : and . as delimiters - the string will be split at each of those chars

    tokens=1-4 => It seems this is grabbing the first four files in a directory no, it grabs the first four tokens of the string (delimited by the defined delims)

    The for /f loop splits it into four tokens: %%t is the first, then down the alphabet: %%u, %%v and %%w

    %%t => Not sure what this means this is the variable name for the (first) token

    ("%TIME: =0%") => No idea what this means it replaces each space in the string with a zero - see set /? for details

    So for each file matching the above criteria, it does this: nothing to do with files here

    set FILENAME=event-%5-%%t%%u%%v%%w => Which i presume means rename each file. no, it creates a variable named filename by concatenating several strings

    What it really does:

    %time% is an internal variable and contains the current time. (Attention, the time format depends on local settings - the code fragment assumes a format of 9:11:22.33 (there is a leading space before the 9)).
    %time: =0% replaces the space, resulting in 09:11:22.33.

    The for /f loop splits this string into four tokens (%%t=09, %%u=11, %%v=22 and %%w=33.

    %5 is the fifth parameter to the batch file (let's assume, it is whatever)

    set FILENAME=event-%5-%%t%%u%%v%%w sets the filename variable to event-whatever-09112233

    I recommend to bookmark SS64 and visit it on a regular basis. You can also get help with every command by executing it with the /? switch (for /?, set /? etc.)