Skip to content

Instantly share code, notes, and snippets.

@mendezcode
Last active October 16, 2020 06:15
Show Gist options
  • Save mendezcode/b3db985309e4656c20cc to your computer and use it in GitHub Desktop.
Save mendezcode/b3db985309e4656c20cc to your computer and use it in GitHub Desktop.
sed.js
var fs = require('fs');
var util = require('util');
function main() {
var args = process.argv.slice(2);
if (args.length === 3) {
var regex = eval(args[0]);
var replace = args[1].replace(/~n/g, "\n").replace(/%(\d+)/g, '$$$1').replace(/%%/g, '%');
var file = args[2];
if (regex instanceof RegExp) {
if (fs.existsSync(file)) {
if (fs.statSync(file).isFile()) {
var buf = fs.readFileSync(file, 'utf8');
var modified = buf.replace(regex, replace);
if (modified != buf) {
fs.writeFileSync(file, modified, 'utf8');
}
}
} else {
console.log(util.format("\nFile not found: %s\n", file));
process.exit();
}
} else {
console.log("\nNot a regular expression: %s\n", args[0]);
process.exit();
}
} else {
console.log("\nUsage: sed.js <regex> <replace> <file>\n");
process.exit();
}
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment