Friday, June 25, 2010

DOS Scripting Text Parsing

I've been most unfortunate to have to be involved in some Windows scripting at work. What is that you say? A colleague of mine recently needed a script that rearranged some images and icons based on some fields in a database. I started off with exporting the database records into a comma separated file.

A few tips about DOS scripting:
  1. One of the best resources on the web on DOS.
  2. REM: Useful for commenting your scripts. I cannot emphasize enough how important it is to comment your scripts.
  3. @echo off: Setting this at the beginning of your script stops the script from printing out the commands it is executing. This makes the output nice and tidy, printing only when echo is called explicitly. Not setting it is good for debugging.
Lets start of with some simple examples and pitfalls:

Parsing text and printing out line numbers:
See the script listing below:

Note that the delims option is set to blank (delims=). This is to counter the fact that spaces and tabs are the default delimiters so you need to override this. Another interesting aspect in the script is the use of the "enabledelayedexpansion". This allows variables in for loops to be evaluated correctly.

Splitting a line delimited by commas
Once your lines have been split, you may want to split the individual lines either by comma (for CSV files) or other delimiters.

This will display the first 3 words of each line after line.

Update: I've found a site with interesting tutorials on DOS.

No comments: