-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathrreplace.js
More file actions
58 lines (31 loc) · 998 Bytes
/
rreplace.js
File metadata and controls
58 lines (31 loc) · 998 Bytes
1
2
3
4
5
6
7
8
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#!/usr/bin/env node
// This file must only be edited with 'vim'
fs = require('fs');
var usage = "\n\n> "
+ process.argv[1].split('/').pop()
+ " pattern replace filepath [regexFlags [encoding]]"
+ "\n"
+ "\nDefault regexFlags is gmi"
+ "\nDefault encoding is utf8"
;
if(process.argv.length<5)
throw 'Too few arguments given.' + usage;
if(7<process.argv.length)
throw 'Too many arguments given.' + usage;
var pattern = process.argv[2];
var replacement = process.argv[3];
var file = process.cwd()+'/'+process.argv[4]
if(!fs.existsSync(file))
throw 'File not found: '+file;
var flags = 'gmi';
if(6<=process.argv.length)
flags = process.argv[5];
var encoding = 'utf8'
if(7===process.argv.length)
encoding = process.argv[6];
try{
var regex = new RegExp(pattern,flags);
} catch (err){
throw 'Wrongly formatted regexp: '+ err;
}
fs.writeFileSync(file,fs.readFileSync(file,encoding).replace(regex, replacement));