\[Editor's Note: Email your scripting solutions (400 words or less) to Reader to Reader at [email protected] Please include your script and phone number. We edit submissions for style, grammar, and length. If we print your contribution, you receive $100.\]
When using the For command to parse text, you use iterator variables to temporarily hold the parsed values. Because you can't use iterator variables outside the For command, the common practice has been to set an iterator variable to a local environment variable when you need to use an iterator variable's value elsewhere in the script. For example, the code in Listing 1 sets the %%i iterator variable to the Group environment variable. The code then uses the Group variable in the :Next subroutine's Echo command to display the value initially in the %%i variable.
As Listing 2 shows, I discovered an interesting trick that you can use to simplify such code. Instead of setting the iterator variable to an environment variable and using the environment variable outside the For command, you can use the iterator variable's value directly. You just need to place the %%i variable after the subroutine call, as callout A in Listing 2 shows. You then specify %* as the Echo command's argument, as callout B in Listing 2 shows. The result is the same—the :Next subroutine's Echo command displays the %%i variable's value.
Using the %* argument is slick when you want to use the value of just one iterator variable. However, the method has limitations if you want to use more than one value. If you want the values of several iterator variables, you can use the approach that Listing 3 illustrates. This code displays all the elements in a parsed line. If you want to display only the first two elements, you can adapt the first line in Listing 3 by replacing "tokens=*" with "tokens=1,2 delims=," and adding %%j at the end of the line.
Another trick I've discovered concerns using the Goto command in Windows 2000 and Windows NT. To jump to the end of a file, many systems administrators use the Goto :EOF command at the appropriate place in the script, then place the :EOF label at the end of the script, as Listing 1 shows. However, because :EOF is a special reserved expression in shell scripting, you don't need to include the :EOF label at the end of the script, as Listing 2 and Listing 3 show.