I have a list of photo captions in a two-column CSV in this format:
"Filename","Caption"
I need to split the CSV into three columns like this
"Filename","Species","Caption"
The regular expression seems to work ok. So I think my usual failure to understand what's happening inside the For Each action is where it's going wrong. Any advice please?
Here are a couple of actions that I wrote to achieve what you want. I did it slightly differently from you because I was intimidated by that long regex. I put the sample material in the For Each text box, but you can change that to a variable easily enough.
I took a look at it. No, it doesn't look okay. I turned on the debugger and found out that the regex you are using is assigning the entire line into the third variable. I usually use the debugger to troubleshoot regex, but most people refer using the website "regex101.com". Or if you want a simpler regex that works, try using my macro instead.
const main = () =>
lines(kmvar.PhotoCSV)
.flatMap(
line => 0 < line.length
? (() => {
const parts = line.split(",");
return [
// Filename.
parts[0],
// Species with end quote.
`${parts[1]}"`,
// Caption with start quote.
[
`"${parts[2].trim()}`,
...parts.slice(3)
]
.join(",")
]
.join(",")
})()
: []
)
.join("\n");
// ----------------------- GENERIC -----------------------
// lines :: String -> [String]
const lines = s =>
// A list of strings derived from a single string
// which is delimited by \n or by \r\n or \r.
0 < s.length
? s.split(/\r\n|\n|\r/u)
: [];
// MAIN ---
return main();
Not sure whether the For Each lines collection depends on finding \n as the line delimiter,
but if it does, I think you may find that the CSV lines in the OP's source are \r delimited.
and I guess another way to use it here (to place the missing " characters),
might be with custom (,) delimiters, and writing to indexed parts, in Keyboard Maestro variable arrays.