-
-
Save krowe/da2a6b021ac891f8e3be to your computer and use it in GitHub Desktop.
@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); | |
} | |
} | |
} |
I've added functionality which allows this to support the -o flag. The -o flag tells the script to display only the matched text instead of the entire line for each match. I've also added an alternate way to specify flags from the command line. The flags -o, -i, -g, -m have been added for these operations.
Sample Useage (find all emails in all *.TXT files):
@echo off
cd "%~dp0"
FOR /R . %%G IN (*.txt) DO @jgrep.bat -o "[A-Za-z0-9/-_.]+@[A-Za-z0-9\-_.]+" < "%%G"
pause
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 %*
.
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
Common Usage Scenario:
Or, if you use my tree script, you can use this to find a specific directory match:
Which could've answered this question at SuperUser.com.
I've added an option -t for converting all single quotes to double quotes before processing. It is otherwise (nearly) impossible to use double quotes.
There is a similar javascript replace script called repl.bat widely available.