Repositorio del curso CCOM4030 el semestre B91 del proyecto Artesanías con el Instituto de Cultura

grep.js 1.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. var common = require('./common');
  2. var fs = require('fs');
  3. //@
  4. //@ ### grep([options ,] regex_filter, file [, file ...])
  5. //@ ### grep([options ,] regex_filter, file_array)
  6. //@ Available options:
  7. //@
  8. //@ + `-v`: Inverse the sense of the regex and print the lines not matching the criteria.
  9. //@
  10. //@ Examples:
  11. //@
  12. //@ ```javascript
  13. //@ grep('-v', 'GLOBAL_VARIABLE', '*.js');
  14. //@ grep('GLOBAL_VARIABLE', '*.js');
  15. //@ ```
  16. //@
  17. //@ Reads input string from given files and returns a string containing all lines of the
  18. //@ file that match the given `regex_filter`. Wildcard `*` accepted.
  19. function _grep(options, regex, files) {
  20. options = common.parseOptions(options, {
  21. 'v': 'inverse'
  22. });
  23. if (!files)
  24. common.error('no paths given');
  25. if (typeof files === 'string')
  26. files = [].slice.call(arguments, 2);
  27. // if it's array leave it as it is
  28. files = common.expand(files);
  29. var grep = '';
  30. files.forEach(function(file) {
  31. if (!fs.existsSync(file)) {
  32. common.error('no such file or directory: ' + file, true);
  33. return;
  34. }
  35. var contents = fs.readFileSync(file, 'utf8'),
  36. lines = contents.split(/\r*\n/);
  37. lines.forEach(function(line) {
  38. var matched = line.match(regex);
  39. if ((options.inverse && !matched) || (!options.inverse && matched))
  40. grep += line + '\n';
  41. });
  42. });
  43. return common.ShellString(grep);
  44. }
  45. module.exports = _grep;