const fs = require('fs'); if (process.argv.length <= 3) { console.log(` ${process.argv.length} Usage: csv-fixer input.csv output.csv `); } else { let [_node, _script, _in, output] = process.argv; console.log('Input/output', _in, output); const re = /\d+/; const input = fs.readFileSync(_in).toString(); const out = []; input.split('\n').forEach((pre, i) => { const l = pre.replace('"', "'"); const count = (l.match(/,/g) || []).length; // console.log(`Count for line ${i} is ${count}`); const items = l.split(','); if (i !== 0) { if (!items[0].trim().match(re)) { console.log('SKIPPING bad line (first item is not number): ', l.trim()); out.push(`BAD,${l.trim()}`); } else { // Skip first line, no need to process if (items[4] !== 'FALSE' && items[4] !== 'TRUE') { // Generate new one with compressed 3 and 4 fields // Find the TRUE or FALSE item let end = 4; let found = false; for (let j = 4; j < items.length; j += 1) { if (items[j] === 'TRUE' || items[j] === 'FALSE') { end = j; found = true; j = items.length; } } if (found) { const fixed = [...items.slice(0, 3), `"${items.slice(3, end).join(',')}"`, ...items.slice(end)].join(','); out.push(fixed); } else { console.log('SKIPPING bad line (unable to find the description followed by a TRUE/FALSE for IsPresenter):', l); out.push(`BAD,${l}`); } } else { out.push(l); } } } else { out.push(l); } }); const corrected = out.join('\n'); fs.writeFileSync(output, corrected); }