Created
August 17, 2021 16:19
-
-
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`
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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