parseQif

parseQif takes a QIF file and generates a csv style file


#!/usr/bin/tclsh
# Jerry LeVan (http://homepage.mac.com/levanj/TclTk/)
# April 4 2004 new file
# On output use this seperator
set sep "|"
#
# The first letter of each line is a Key, we are interested in
# D (Date) T (Amount) N (TranID) P (Source) M (Memo) C (Status) L (Category)
#
set keys "DTNPMCL"
set keyList [split $keys ""]
#
# get the filename
#
  if {$argc} {
     set f [lindex $argv 0]
  } else {
    puts "useage: parseQif <filename>" 
    return 1
  }
#
# open the file
#
   set input [open $f "r"]

# get an output file by replacing .qif by .csv
  if { ! [regsub -nocase {\.qif$} $f {.csv} outFile ] } {
    set outFile [append f ".csv"]
  }
  set output [open $outFile "w"]  
#
# read the file into a big string
#
   set theFile [read $input]
   close $input

   regsub -all {\n\^\n} $theFile {^} chunks
   set chunks [split $chunks "^"]
   set chunks [lrange $chunks 1 end-1]

   foreach item $chunks {
      set itemList [split $item "\n"]
      unset -nocomplain keyArray
      foreach ch $keyList {
        set keyArray($ch) ""
      }
      foreach detail $itemList {
        set key [string index $detail 0]
        set value [string range $detail 1 end]
        set keyArray($key) $value
      }
    unset -nocomplain line
    foreach ch $keyList {
      append line $keyArray($ch) $sep
    }
    set line [string range $line 0 end-1]
    puts $output $line
   }
   close $output