Tuesday, May 22, 2012

vbscript gerp utility


DisplayLineNumber = False
ExactMatch = False
IgnoreCase = True

Set oFSO = CreateObject("Scripting.FileSystemObject")


if WScript.Arguments.Count = 0 Then
    Wscript.StdOut.Writeline "Incorrect arguments. syntax: egrep  [filename] [-n] [-x] [-cs]"
    Wscript.StdOut.Writeline "-n          : Display Line Number"
    Wscript.StdOut.Writeline "-x          : Exact Match"
    Wscript.StdOut.Writeline "-cs         : Case Sensitive. By Default it ignore Case"
    Wscript.StdOut.Writeline "Example: egrep @ EULA.txt" & vbNewLine & "Example: egrep /b.*@gmail.com EULA.txt -n -x -cs" & vbnewline & "Example: ipconfig | egrep ""IP Add"""

    Wscript.Quit
Else
    Pattern = WScript.Arguments.item(0)

    if WScript.Arguments.Count => 2 Then
 FileName = WScript.Arguments.item(1)
 if oFSO.FileExists(FileName) Then
  Set oInputStream = oFSO.OpenTextFile(FileName,1)
 Else
  Set oInputStream = Wscript.Stdin
 End if
    Else
 Set oInputStream = Wscript.Stdin
    End if

    For i = 0 to  (WScript.Arguments.Count - 1)
        Select Case Lcase(WScript.Arguments.item(i))
        Case "-n" DisplayLineNumber = True
        Case "-x" ExactMatch = True
        Case "-cs" IgnoreCase = False
        Case Else
        End Select

    Next


End if




Dim StrLine, LineCount

if Pattern = "*" Then : Pattern = ".*" : End If

Set oRegX = New RegExp

oRegX.Pattern = Pattern
oRegX.IgnoreCase = IgnoreCase
oRegX.Global = True

LineCount = 0

Do Until oInputStream.AtEndOfStream
        StrLine = oInputStream.ReadLine
 TextToPrint = ""
        LineCount = LineCount + 1
        Set oMatches = oRegX.Execute(StrLine)

        if oRegX.Test(StrLine) Then
            Set oMatches = oRegX.Execute(StrLine)
            if ExactMatch then
                For each oMatch in oMatches
                    TextToPrint = TextToPrint & oMatch.Value
                Next
            else
                TextToPrint = StrLine
            end if
            
            If DisplayLineNumber Then
                TextToPrint = LineCount & "::" & TextToPrint
            End if
            Wscript.StdOut.WriteLine TextToPrint

        End if

Loop

'================ BAT ===============

@echo off
Set CurrentDirectory=%~dp0
cscript //nologo %CurrentDirectory%egrepvbs.vbs %1 %2 %3 %4
Save bat file in a folder present in path variable

No comments:

Post a Comment