Skip to content

Instantly share code, notes, and snippets.

@antonk52
Created August 17, 2021 16:19
Show Gist options
  • Save antonk52/530149ed62f7f29b0763d052a7d97f7d to your computer and use it in GitHub Desktop.
Save antonk52/530149ed62f7f29b0763d052a7d97f7d to your computer and use it in GitHub Desktop.
parse `rg --json` output and output as unified json array to be able to work with it using `jq`
let string = '';
process.stdin.on('data', data => {
string += data;
});
process.stdin.on('close', data => {
const map = parseString(string)
.filter(t => t.type === 'match')
.map(x => x.data.submatches[0].match.text)
.reduce((acc, el) => {
const path = el.match(/'(.+)';$/)[0];
if (path in acc) {
acc[path]++;
} else {
acc[path] = 1;
}
return acc;
}, {});
console.log(Object.entries(map).sort((a, b) => a[1] - b[1]))
});
function parseString(s) {
let str = s;
const result = [];
while (str.length > 100) {
try {
result.push(JSON.parse(str));
break;
} catch (e) {
const stringErr = e.toString();
const match = stringErr.match(/\d+$/);
if (match) {
const pos = match[0];
try {
result.push(JSON.parse(str.slice(0, pos)));
str = str.slice(pos);
} catch (er) {
console.error('specific parse failed', er);
break;
}
} else {
console.log('no match', stringErr);
break;
}
}
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment