sed.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. var common = require('./common');
  2. var fs = require('fs');
  3. common.register('sed', _sed, {
  4. globStart: 3, // don't glob-expand regexes
  5. canReceivePipe: true,
  6. cmdOptions: {
  7. 'i': 'inplace',
  8. },
  9. });
  10. //@
  11. //@ ### sed([options,] search_regex, replacement, file [, file ...])
  12. //@ ### sed([options,] search_regex, replacement, file_array)
  13. //@ Available options:
  14. //@
  15. //@ + `-i`: Replace contents of 'file' in-place. _Note that no backups will be created!_
  16. //@
  17. //@ Examples:
  18. //@
  19. //@ ```javascript
  20. //@ sed('-i', 'PROGRAM_VERSION', 'v0.1.3', 'source.js');
  21. //@ sed(/.*DELETE_THIS_LINE.*\n/, '', 'source.js');
  22. //@ ```
  23. //@
  24. //@ Reads an input string from `files` and performs a JavaScript `replace()` on the input
  25. //@ using the given search regex and replacement string or function. Returns the new string after replacement.
  26. //@
  27. //@ Note:
  28. //@
  29. //@ Like unix `sed`, ShellJS `sed` supports capture groups. Capture groups are specified
  30. //@ using the `$n` syntax:
  31. //@
  32. //@ ```javascript
  33. //@ sed(/(\w+)\s(\w+)/, '$2, $1', 'file.txt');
  34. //@ ```
  35. function _sed(options, regex, replacement, files) {
  36. // Check if this is coming from a pipe
  37. var pipe = common.readFromPipe();
  38. if (typeof replacement !== 'string' && typeof replacement !== 'function') {
  39. if (typeof replacement === 'number') {
  40. replacement = replacement.toString(); // fallback
  41. } else {
  42. common.error('invalid replacement string');
  43. }
  44. }
  45. // Convert all search strings to RegExp
  46. if (typeof regex === 'string') {
  47. regex = RegExp(regex);
  48. }
  49. if (!files && !pipe) {
  50. common.error('no files given');
  51. }
  52. files = [].slice.call(arguments, 3);
  53. if (pipe) {
  54. files.unshift('-');
  55. }
  56. var sed = [];
  57. files.forEach(function (file) {
  58. if (!fs.existsSync(file) && file !== '-') {
  59. common.error('no such file or directory: ' + file, 2, { continue: true });
  60. return;
  61. }
  62. var contents = file === '-' ? pipe : fs.readFileSync(file, 'utf8');
  63. var lines = contents.split(/\r*\n/);
  64. var result = lines.map(function (line) {
  65. return line.replace(regex, replacement);
  66. }).join('\n');
  67. sed.push(result);
  68. if (options.inplace) {
  69. fs.writeFileSync(file, result, 'utf8');
  70. }
  71. });
  72. return sed.join('\n');
  73. }
  74. module.exports = _sed;