Main Content

Extracting data from a string / line from file - Tcl

Archive - Originally posted on "The Horse's Mouth" - 2011-05-10 19:09:37 - Graham Ellis

I never cease to be amazed at the number of different ways that data can be encoded into simple test lines ... and how the various languages that we teach can be used to manipulate / extract pertinent information. Today, on a Tcl Course, I was presented with data in this form:
  T/N/R/Brother/Sister/Mum/Bob.txt/Esmerelda.txt/Sophie.txt

The first three fields can be disregarded. The rest of the line lists a series of relationships (and unspecified number from 0 up) followed by a series of file names, each of which relates to a relationship. Nothing nice like them being in pairs on the line - it's all the relationships followed by all the file names.

Solution?
 1. Reformat the line into a list with split
 2. Calculate the number of relationships with expr
 3. Loop (a for loop) through each relationship
 4. In the loop, calculate positions of the relationship and file name with expr
 5. Extract the field you want with lindex
Complete source code example [here]