feat(grep): add -l option

`grep -l` will only print filenames of matching files.
This commit is contained in:
Nate Fischer 2016-02-09 09:23:17 -08:00
parent bc13470f91
commit 3ea5e247ee
3 changed files with 24 additions and 8 deletions

View File

@ -370,6 +370,7 @@ using the given search regex and replacement string or function. Returns the new
Available options:
+ `-v`: Inverse the sense of the regex and print the lines not matching the criteria.
+ `-l`: Print only filenames of matching files
Examples:

View File

@ -7,6 +7,7 @@ var fs = require('fs');
//@ Available options:
//@
//@ + `-v`: Inverse the sense of the regex and print the lines not matching the criteria.
//@ + `-l`: Print only filenames of matching files
//@
//@ Examples:
//@
@ -19,7 +20,8 @@ var fs = require('fs');
//@ file that match the given `regex_filter`. Wildcard `*` accepted.
function _grep(options, regex, files) {
options = common.parseOptions(options, {
'v': 'inverse'
'v': 'inverse',
'l': 'nameOnly'
});
if (!files)
@ -31,7 +33,7 @@ function _grep(options, regex, files) {
files = common.expand(files);
var grep = '';
var grep = [];
files.forEach(function(file) {
if (!fs.existsSync(file)) {
common.error('no such file or directory: ' + file, true);
@ -40,13 +42,18 @@ function _grep(options, regex, files) {
var contents = fs.readFileSync(file, 'utf8'),
lines = contents.split(/\r*\n/);
lines.forEach(function(line) {
var matched = line.match(regex);
if ((options.inverse && !matched) || (!options.inverse && matched))
grep += line + '\n';
});
if (options.nameOnly) {
if (contents.match(regex))
grep.push(file);
} else {
lines.forEach(function(line) {
var matched = line.match(regex);
if ((options.inverse && !matched) || (!options.inverse && matched))
grep.push(line);
});
}
});
return common.ShellString(grep);
return common.ShellString(grep.join('\n')+'\n');
}
module.exports = _grep;

View File

@ -83,4 +83,12 @@ var result = shell.grep('l*\\.js', 'resources/grep/file');
assert.equal(shell.error(), null);
assert.equal(result, 'this line ends in.js\nlllllllllllllllll.js\n');
// -l option
result = shell.grep('-l', 'test1', 'resources/file1', 'resources/file2', 'resources/file1.txt');
assert.equal(shell.error(), null);
assert.ok(result.match(/file1(\n|$)/));
assert.ok(result.match(/file1.txt/));
assert.ok(!result.match(/file2.txt/));
assert.equal(result.split('\n').length - 1, 2);
shell.exit(123);