UNPKG

2.55 kBJavaScriptView Raw
1var common = require('./common');
2var fs = require('fs');
3
4// add c spaces to the left of str
5function lpad(c, str) {
6 var res = '' + str;
7 if (res.length < c) {
8 res = Array((c - res.length) + 1).join(' ') + res;
9 }
10 return res;
11}
12
13common.register('uniq', _uniq, {
14 canReceivePipe: true,
15 cmdOptions: {
16 'i': 'ignoreCase',
17 'c': 'count',
18 'd': 'duplicates',
19 },
20});
21
22//@
23//@ ### uniq([options,] [input, [output]])
24//@ Available options:
25//@
26//@ + `-i`: Ignore case while comparing
27//@ + `-c`: Prefix lines by the number of occurrences
28//@ + `-d`: Only print duplicate lines, one for each group of identical lines
29//@
30//@ Examples:
31//@
32//@ ```javascript
33//@ uniq('foo.txt');
34//@ uniq('-i', 'foo.txt');
35//@ uniq('-cd', 'foo.txt', 'bar.txt');
36//@ ```
37//@
38//@ Filter adjacent matching lines from input
39function _uniq(options, input, output) {
40 // Check if this is coming from a pipe
41 var pipe = common.readFromPipe();
42
43 if (!pipe) {
44 if (!input) common.error('no input given');
45
46 if (!fs.existsSync(input)) {
47 common.error(input + ': No such file or directory');
48 } else if (common.statFollowLinks(input).isDirectory()) {
49 common.error("error reading '" + input + "'");
50 }
51 }
52 if (output && fs.existsSync(output) && common.statFollowLinks(output).isDirectory()) {
53 common.error(output + ': Is a directory');
54 }
55
56 var lines = (input ? fs.readFileSync(input, 'utf8') : pipe).
57 trimRight().
58 split('\n');
59
60 var compare = function (a, b) {
61 return options.ignoreCase ?
62 a.toLocaleLowerCase().localeCompare(b.toLocaleLowerCase()) :
63 a.localeCompare(b);
64 };
65 var uniqed = lines.reduceRight(function (res, e) {
66 // Perform uniq -c on the input
67 if (res.length === 0) {
68 return [{ count: 1, ln: e }];
69 } else if (compare(res[0].ln, e) === 0) {
70 return [{ count: res[0].count + 1, ln: e }].concat(res.slice(1));
71 } else {
72 return [{ count: 1, ln: e }].concat(res);
73 }
74 }, []).filter(function (obj) {
75 // Do we want only duplicated objects?
76 return options.duplicates ? obj.count > 1 : true;
77 }).map(function (obj) {
78 // Are we tracking the counts of each line?
79 return (options.count ? (lpad(7, obj.count) + ' ') : '') + obj.ln;
80 }).join('\n') + '\n';
81
82 if (output) {
83 (new common.ShellString(uniqed)).to(output);
84 // if uniq writes to output, nothing is passed to the next command in the pipeline (if any)
85 return '';
86 } else {
87 return uniqed;
88 }
89}
90
91module.exports = _uniq;