Batch Files: Tokens and Delimiters (FOR Loops)

Quite often when writing a batch file, you will come across a FOR loop. It might look something like this:

FOR /f "tokens=* delims= " %%a IN (MyFile) DO ECHO %%a

I am constantly hearing people asking "What do tokens and delims mean?". Well, here you are.

Tokens and delimiters in action

Tokens basically tell the batch file where to look to set the variable (%a). Delimiters are what separate each token. It's a little difficult to explain, so here's an example.

A file, called MyFile, contains this:

Hello World! How are you doing today?

Now, let's pretend that we want is the word "World!". How will we accomplish that? Using a space as a delimiter (separator) we can grab it with the second token.

FOR /f "tokens=2 delims= " %%a IN (MyFile.txt) DO ECHO %%a

Grabbing a range

Now let's say that we want the "How are you doing today?" portion. Still using space as a delimiter, we can grab it with tokens 3-7.

FOR /f 'tokens=3-7 delims= " %%a IN (MyFile.txt) DO ECHO %%a %%b %%c %%d %%e

Notice the variables. The batch file sets the first variable defined (%a) then will move on to the next one, in this case %b.

If I wanted to, I could set all the variables, then just echo %a %c %e, resulting in "How you today?"

Variations on a range

Now, just because we've decided to become very aggressive, we're going to attempt to get the words "Hello", "How", and "doing". Using the same logic as before, we can use the first, third, and sixth token.

FOR /f 'tokens=1, 3, 6 delims= " %%a IN (MyFile.txt) DO ECHO %%a %%b %%c

Again, notice the variables (See above).

Taking everything

We can set the entire line if we want to, using an asterisk (*).

FOR /f "tokens=* delims= " %%a IN (MyFile.txt) DO ECHO %%a

The asterisk, sets every token to the variable.

Another example

A delimiter can be anything, for example, if I have a text file containing:

Hello World! /How are you today?/

I could grab just the part enclosed within the backslash using this:

FOR /f "tokens=2 delims=/" %%a IN (MyFile) DO ECHO %%a

Notice haw I used the second token. This is because the first would be what ever is in from of the first slash ("Hello World! ") is set as the first.

Try it out yourself!

Do not be discouraged if you do not understand it all at once, it can be confusing. Give it a few tries, and write a few samples to help yourself learn.

Good luck.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值