MACRO: Parse CSV Line [Example]
VER: 3.0 2016-11-13 ~~~
DOWNLOAD:
Parse CSV Line [Example].kmmacros (10.0 KB)
ReleaseNotes
PURPOSE: Extract One Line of CSV Data, & Set KM Variables
A KM Variable will be set for each CSV Field Found
RETURN list of KM Variable names and values
VER: 2.0 2016-08-17
METHOD: Use JXA script to find CSV fields using:
- Default RegEx:
(.+?)(?:, ?|$)
- Comma MUST immediately follow value
- An optional space may appear after comma
- RegEx for values in quotes:
"([^"]*)"
AUTHOR:
* @JMichaelTX
* Based on macro/script by @DanThomas
MACRO SETUP:
- Change the below two "Set Variable" Actions to use your data
See Header Comments in below script for more info.
Example Results
# Script
/*
---
PURPOSE: Extract One Line of CSV Data, & Set KM Variables
RETURN List of KM Variables and Values
VER: 3.0 2016-11-14
AUTHOR:
• @DanThomas -- Ver 1 which extracted and returned the data, one line per item
* @JMichaelTX -- Ver 3 which ADDED Set of KM Variables, and get RegEx from KM
KM VARIABALES REQUIRED:
• csvLine
• csvVarPrefix
• csvRegEx
KM VARIABLES SET:
• One Variable for each match found of CSV data
• Variable Name: csvVarPrefix + sequence#
(Example: TEST_myVar_2)
REF:
• Search Variable using Regular Expression
https://forum.keyboardmaestro.com/t/search-variable-using-regular-expression/4704
---
*/
(function() {
'use strict';
try {
var kme = Application("Keyboard Maestro Engine");
var input = kme.getvariable("csvLine") // || '"TEST one","TEST two","TEST three"';
var kmVarPrefix = kme.getvariable("csvVarPrefix") || 'TEST_myVar_';
var regExStr = kme.getvariable("csvRegEx") || "(.+?)(?:, ?|$)";
if (!input)
throw Error("Variable '" + csvLine + "' is empty");
var regexp = new RegExp(regExStr,"g");
var matches;
var matchList = [];
//while ((matches = regexp.exec(input))[1] !=="") {
while ((matches = regexp.exec(input)) !== null) {
matchList.push(matches[1]);
}
var kmVar = ""
var numMatches = matchList.length;
console.log("Number of Matches: " + numMatches);
for (var iMatch = 0; iMatch < numMatches; iMatch++) {
kmVar = kmVarPrefix + (iMatch+1).toString(); // ADD a numeric suffix to variable name
console.log(kmVar + ": " + matchList[iMatch])
//--- SET THE KM VARIABLE ---
kme.setvariable(kmVar, { to: matchList[iMatch] });
} // END for matchList
return // matchList.join("\n")
} catch (e) {
return "[**ERROR**] " + e.message;
}
})();