UNPKG

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