diff --git a/README.md b/README.md index 4e35fa3..a25dd8f 100644 --- a/README.md +++ b/README.md @@ -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: diff --git a/src/grep.js b/src/grep.js index 78008ce..cdfc35a 100644 --- a/src/grep.js +++ b/src/grep.js @@ -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; diff --git a/test/grep.js b/test/grep.js index 267a989..bfbc7c0 100644 --- a/test/grep.js +++ b/test/grep.js @@ -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);