Skip to content

Instantly share code, notes, and snippets.

@shanebarringer
Forked from mendezcode/sed.js
Last active August 27, 2018 14:53
Show Gist options
  • Save shanebarringer/5c3f4a5ee5c22c28940f9022bcef4cbd to your computer and use it in GitHub Desktop.
Save shanebarringer/5c3f4a5ee5c22c28940f9022bcef4cbd to your computer and use it in GitHub Desktop.
forked from sed.js
#! /bin/node
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