Skip to content

Instantly share code, notes, and snippets.

@krowe
Last active January 6, 2021 19:05
Show Gist options
  • Save krowe/da2a6b021ac891f8e3be to your computer and use it in GitHub Desktop.
Save krowe/da2a6b021ac891f8e3be to your computer and use it in GitHub Desktop.
A RegEx match script which uses Hybrid Batch\JScript code
@set @junk=1 /*
@cscript //nologo //E:jscript %~f0 %*
@goto :eof */
var args=WScript.Arguments, argCnt=args.Length, stdin=WScript.StdIn, stdout=WScript.StdOut;
var replaceSingleQuotes=false, printMatchesOnly=false, matchString, flagString, regex, argDx=0;
if(argCnt==0) {
throw new Error("You must provide search criteria.");
}
flagString=""
if(argCnt>1) {
for(var bLoop=true; bLoop&&argDx<argCnt-1; argDx++) {
switch(args(argDx)) {
case '-t': replaceSingleQuotes=true; break;
case '-o': printMatchesOnly=true; break;
case '-g': flagString+="g"; break;
case '-i': flagString+="i"; break;
case '-m': flagString+="m"; break;
default: bLoop=false; break;
}
}
}
if(replaceSingleQuotes) {
matchString=args(argCnt-1).replace("'", '"');
} else {
matchString=args(argCnt-1);
}
if(printMatchesOnly) {
while(!stdin.AtEndOfStream) {
var sLine=stdin.ReadLine();
if(flagString.Length) regex=new RegExp(matchString, flagString);
else regex=new RegExp(matchString);
var m,matches=[],startDx=0;
while((m=regex.exec(sLine.substr(startDx))) !== null) {
stdout.WriteLine(m[0]);
startDx+=m.lastIndex;
}
}
} else {
if(flagString.Length) regex=new RegExp(matchString, flagString);
else regex=new RegExp(matchString);
while(!stdin.AtEndOfStream) {
var sLine=stdin.ReadLine();
if(regex.test(sLine)) {
stdout.WriteLine(sLine);
}
}
}
@krowe
Copy link
Author

krowe commented Dec 27, 2014

I've fixed this script so that it can be called without the .bat extension. To do this in your own scripts replace cscript //nologo //E:jscript %0 %* with cscript //nologo //E:jscript %~f0 %*.

@VIVEKLUCKY249
Copy link

Hello krowe!!!

Please read my question on Super User about Find “mystring” in files and return only certain portion of matching lines.

Can your tool solve my issue ? Please explain how, in more detail.

Please reply asap!!!

Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment