“I have an AppleScript below that allows writing cell/reading cell/deleting columns/deleting rows in a CSV table. The script works. But when I want to write text with commas into a cell, e.g., ‘a1, 2, 3,’ the entire table breaks. I have tried several AI tools but haven’t found a solution. Could you please help me fix this script?”
Created by Perplexity.ai:
on csvEdit(action, rowIdx, colIdx, value, csvPath)
set csvText to (do shell script "iconv -f utf-8 -t utf-8 " & quoted form of POSIX path of csvPath)
set csvLines to paragraphs of csvText
set csvData to {}
repeat with l in csvLines
set end of csvData to (my splitText(l, ","))
end repeat
if action is "read" then
if rowIdx ≥ 1 and rowIdx ≤ (count csvData) then
set rowList to item rowIdx of csvData
if colIdx ≥ 1 and colIdx ≤ (count rowList) then
return item colIdx of rowList
end if
end if
return ""
else if action is "write" then
if rowIdx ≥ 1 and rowIdx ≤ (count csvData) then
set rowList to item rowIdx of csvData
if colIdx ≥ 1 and colIdx ≤ (count rowList) then
set item colIdx of rowList to value
set item rowIdx of csvData to rowList
end if
end if
else if action is "delrow" then
if rowIdx ≥ 1 and rowIdx ≤ (count csvData) then
if rowIdx = 1 then
set csvData to items 2 thru (count csvData) of csvData
else if rowIdx = (count csvData) then
set csvData to items 1 thru (rowIdx - 1) of csvData
else
set csvData to (items 1 thru (rowIdx - 1) of csvData) & (items (rowIdx + 1) thru (count csvData) of csvData)
end if
end if
else if action is "delcol" then
repeat with i from 1 to count csvData
set rowList to item i of csvData
if colIdx ≥ 1 and colIdx ≤ (count rowList) then
if colIdx = 1 then
set rowList to items 2 thru (count rowList) of rowList
else if colIdx = (count rowList) then
set rowList to items 1 thru (colIdx - 1) of rowList
else
set rowList to (items 1 thru (colIdx - 1) of rowList) & (items (colIdx + 1) thru (count rowList) of rowList)
end if
end if
set item i of csvData to rowList
end repeat
end if
set outText to ""
repeat with r in csvData
set outText to outText & (my joinText(r, ",")) & linefeed
end repeat
do shell script "echo " & quoted form of outText & " | iconv -f utf-8 -t utf-8 > " & quoted form of POSIX path of csvPath
return "OK"
end csvEdit
-- Split and join
on splitText(txt, delim)
set AppleScript's text item delimiters to delim
set outList to text items of txt
set AppleScript's text item delimiters to ""
return outList
end splitText
on joinText(lst, delim)
set AppleScript's text item delimiters to delim
set outText to lst as string
set AppleScript's text item delimiters to ""
return outText
end joinText
-- CSV file
set csvPath to "/Users/adam/Desktop/test.csv"
-- Read: [D1]
set val to csvEdit("read", 1, 4, "", csvPath)
display dialog val
-- Write: [D1]
csvEdit("write", 1, 4, "New value", csvPath)
-- Delete: row (3)
csvEdit("delrow", 3, 0, "", csvPath)
-- Delete: column (5)
csvEdit("delcol", 0, 5, "", csvPath)