1 | var common = require('./common');
|
2 | var fs = require('fs');
|
3 |
|
4 | common.register('sed', _sed, {
|
5 | globStart: 3,
|
6 | canReceivePipe: true,
|
7 | cmdOptions: {
|
8 | 'i': 'inplace',
|
9 | },
|
10 | });
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 |
|
31 |
|
32 |
|
33 |
|
34 |
|
35 |
|
36 |
|
37 | function _sed(options, regex, replacement, files) {
|
38 |
|
39 | var pipe = common.readFromPipe();
|
40 |
|
41 | if (typeof replacement !== 'string' && typeof replacement !== 'function') {
|
42 | if (typeof replacement === 'number') {
|
43 | replacement = replacement.toString();
|
44 | } else {
|
45 | common.error('invalid replacement string');
|
46 | }
|
47 | }
|
48 |
|
49 |
|
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 | }
|
86 | module.exports = _sed;
|