Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Microsoft JScript - Search and replace in a text file using regex
try
{
var fso = new ActiveXObject("Scripting.FileSystemObject");
var shell = new ActiveXObject("WScript.Shell");
var READ = 1, WRITE = 2, APPEND = 8;
var TEXT_DEFAULT = -2, TEXT_UNICODE = -1, TEXT_ANSI = 0;
var argc = WScript.Arguments.Count();
if (argc < 4)
{
WScript.Echo("<infile> <outfile> <search> <replace> [flags]");
WScript.Quit(1);
}
var infile = WScript.Arguments.Item(0);
var outfile = WScript.Arguments.Item(1);
var search = WScript.Arguments.Item(2);
var replace = WScript.Arguments.Item(3);
var flags = "";
if (argc > 4)
{
flags = WScript.Arguments.Item(4);
}
var quiet = flags.search("q") > -1;
var reflags = flags.replace("q", "");
if (!quiet)
{
WScript.Echo("infile :", infile);
WScript.Echo("outfile:", outfile);
WScript.Echo("search :", search);
WScript.Echo("replace:", replace);
WScript.Echo("flags :", flags);
}
var regex = new RegExp(search, reflags);
file = fso.OpenTextFile(infile, READ);
str = file.ReadAll();
file.Close();
str = str.replace(regex, replace);
file = fso.OpenTextFile(outfile, WRITE, true);
file.Write(str);
file.Close();
}
catch(ex)
{
WScript.Echo(ex.name + ": " + ex.description + " / "
+ ex.message + " (" + ex.number + ")");
WScript.Quit(1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment