For a project I’m working on, I’m reading lines from a CSV (Comma Separated Values) file, reordering the data, adding and removing some data, and eventually will output each line as a SQL insert statement. I have no control over the format of the incoming data as it is generated elsewhere.
The data looks something like this:
Fall 2006,BIOL,195J,6,1,INTRO TO BIOLOGY,XXXXX-XXXXX,"Last,First,Middle",LAST,FIRST,M,1,LA,,,910,B6,
As you can see, they include the student’s full name inside quotes but also separated by commas. Using comma as a text delimiter gives me:
{"Fall 2006", "BIOL", "195J" ,"6", "1", "INTRO TO BIOLOGY", "XXXXX-XXXXX", ""Last", "First", "Middle"", "LAST", "FIRST", "M", "1", "LA", "", "", "910","B6"}
This would be fine, except that SOME of the lines don’t include the Middle name so the number of items in the array is not constant. (Oy!)
What I need is some clever way to get Applescript to treat “Last,First,Middle” as one delimited item rather than three (or ignore it all together).
My first thought was to somehow use " as a delimiter to split the original data into three pieces, drop the middle, concatenate them back together, change the delimiter to ‘,’ and then proceed from there. My second thought was to count the number of items in the array since it should be 20 with a middle name and 19 without. But I’m loathe to trust that this will be true for all cases.
I’m hoping there’s a more elegant solution.
Here’s what I have for the moment (for reference).
repeat
try
set s_temp to read aFile until eol -- (eol = "\n")
set {myTID, AppleScript's text item delimiters} to {AppleScript's text item delimiters, {","}}
set temp to text items of s_temp
set AppleScript's text item delimiters to myTID
set SQL_data to {item 7 of temp, item 2 of temp, item 3 of temp, item 4 of temp, "I AGREE", item 10 of temp, item 9 of temp, item 11 of temp, item 13 of temp, item 5 of temp, item 1 of temp, item 2 of temp, item 6 of temp, prof1, prof2} -- (prof1 and prof2 are set earlier in the code)
on error
display dialog "Error"
exit repeat
end try
end repeat
Thanks in advance!!