Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit a7ee6a2

Browse files
freitagbrnfischer
authored andcommitted
fix(grep, sed, sort, uniq): Split only on newline characters (#690)
* Split on newlines only * Only split lines if need be * Clarify code by making use of Array.prototype.reduce
1 parent dc99a91 commit a7ee6a2

File tree

4 files changed

+7
-9
lines changed

4 files changed

+7
-9
lines changed

src/grep.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,12 +47,12 @@ function _grep(options, regex, files) {
4747
}
4848

4949
var contents = file === '-' ? pipe : fs.readFileSync(file, 'utf8');
50-
var lines = contents.split(/\r*\n/);
5150
if (options.nameOnly) {
5251
if (contents.match(regex)) {
5352
grep.push(file);
5453
}
5554
} else {
55+
var lines = contents.split('\n');
5656
lines.forEach(function (line) {
5757
var matched = line.match(regex);
5858
if ((options.inverse && !matched) || (!options.inverse && matched)) {

src/sed.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ function _sed(options, regex, replacement, files) {
6969
}
7070

7171
var contents = file === '-' ? pipe : fs.readFileSync(file, 'utf8');
72-
var lines = contents.split(/\r*\n/);
72+
var lines = contents.split('\n');
7373
var result = lines.map(function (line) {
7474
return line.replace(regex, replacement);
7575
}).join('\n');

src/sort.js

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -67,19 +67,17 @@ function _sort(options, files) {
6767
files.unshift('-');
6868
}
6969

70-
var lines = [];
71-
files.forEach(function (file) {
70+
var lines = files.reduce(function (accum, file) {
7271
if (!fs.existsSync(file) && file !== '-') {
7372
// exit upon any sort of error
7473
common.error('no such file or directory: ' + file);
7574
}
7675

7776
var contents = file === '-' ? pipe : fs.readFileSync(file, 'utf8');
78-
lines = lines.concat(contents.trimRight().split(/\r*\n/));
79-
});
77+
return accum.concat(contents.trimRight().split('\n'));
78+
}, []);
8079

81-
var sorted;
82-
sorted = lines.sort(options.numerical ? numericalCmp : unixCmp);
80+
var sorted = lines.sort(options.numerical ? numericalCmp : unixCmp);
8381

8482
if (options.reverse) {
8583
sorted = sorted.reverse();

src/uniq.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ function _uniq(options, input, output) {
4444

4545
var lines = (input ? fs.readFileSync(input, 'utf8') : pipe).
4646
trimRight().
47-
split(/\r*\n/);
47+
split('\n');
4848

4949
var compare = function (a, b) {
5050
return options.ignoreCase ?

0 commit comments

Comments
 (0)