UNPKG

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