diff --git a/README.md b/README.md index ff58d9a..399a27d 100644 --- a/README.md +++ b/README.md @@ -267,12 +267,16 @@ sed(/.*DELETE_THIS_LINE.*\n/, '', 'source.js'); Reads an input string from `file` and performs a JavaScript `replace()` on the input using the given search regex and replacement string. Returns the new string after replacement. -#### grep(regex_filter, file [, file ...]) -#### grep(regex_filter, file_array) +#### grep([options ,] regex_filter, file [, file ...]) +#### grep([options ,] regex_filter, file_array) +Available options: + ++ `-v`: Inverse the sense of the regex and print the lines not matching the criteria. Examples: ```javascript +grep('-v', 'GLOBAL_VARIABLE', '*.js'); grep('GLOBAL_VARIABLE', '*.js'); ``` @@ -368,3 +372,4 @@ Returns true if all the given paths exist. _This function is being deprecated. Use `silent(false) instead.`_ Enables all output (default) + diff --git a/shell.js b/shell.js index 72478c4..923be9a 100644 --- a/shell.js +++ b/shell.js @@ -659,18 +659,26 @@ function _sed(options, regex, replacement, file) { exports.sed = wrap('sed', _sed); //@ -//@ #### grep(regex_filter, file [, file ...]) -//@ #### grep(regex_filter, file_array) +//@ #### grep([options ,] regex_filter, file [, file ...]) +//@ #### grep([options ,] regex_filter, file_array) +//@ Available options: +//@ +//@ + `-v`: Inverse the sense of the regex and print the lines not matching the criteria. //@ //@ Examples: //@ //@ ```javascript +//@ grep('-v', 'GLOBAL_VARIABLE', '*.js'); //@ grep('GLOBAL_VARIABLE', '*.js'); //@ ``` //@ //@ Reads input string from given files and returns a string containing all lines of the //@ file that match the given `regex_filter`. Wildcard `*` accepted. function _grep(options, regex, files) { + options = parseOptions(options, { + 'v': 'inverse' + }); + if (!files) error('no paths given'); @@ -690,7 +698,8 @@ function _grep(options, regex, files) { var contents = fs.readFileSync(file, 'utf8'), lines = contents.split(/\r*\n/); lines.forEach(function(line) { - if (line.match(regex)) + var matched = line.match(regex); + if ((options.inverse && !matched) || (!options.inverse && matched)) grep += line + '\n'; }); }); diff --git a/test/grep.js b/test/grep.js index e401f08..498d353 100644 --- a/test/grep.js +++ b/test/grep.js @@ -38,6 +38,10 @@ var result = shell.grep('line', 'resources/a.txt'); assert.equal(shell.error(), null); assert.equal(result.split('\n').length - 1, 4); +var result = shell.grep('-v', 'line', 'resources/a.txt'); +assert.equal(shell.error(), null); +assert.equal(result.split('\n').length - 1, 8); + var result = shell.grep('line one', 'resources/a.txt'); assert.equal(shell.error(), null); assert.equal(result, 'This is line one\n');