Sarathi Kamaraj
Sarathi Kamaraj

Reputation: 697

extract numbers before search string in a file

My log looks like this

2013-10-22 11:29:44 +02:00 - Info - Resultate 
2013-10-22 11:29:44 +02:00 - Info - 1502 lines imported 
2013-10-22 11:29:44 +02:00 - Info - 1 header lines 
2013-10-22 11:29:44 +02:00 - Info - 1563 errors
2013-10-22 11:29:44 +02:00 - Info - 0 changed 
2013-10-22 11:29:44 +02:00 - Info - 0 deleted 
2013-10-22 11:29:44 +02:00 - Info - 0 not changed 
2013-10-22 11:29:44 +02:00 - Info - 0 not found1-1 
2013-10-22 11:29:44 +02:00 - Info - 1 empty lines 
2013-10-22 11:29:44 +02:00 - Info - 1499 errors 

I am new to VBScribt and in need of writing a script to get the numbers before the word errors in this files.

My expected output is

1563
1499

I tried searching and was not able to get a similar scenario.

Please assist me.

Upvotes: 0

Views: 309

Answers (3)

MC ND
MC ND

Reputation: 70951

Better way to process log files is to leave the work to the correct tools. But when we dont have access to this tools, second best option is to try to read as less information into script as possible. Log files are usually really big. So, instead of reading and searching with script code, let the system do the work for you. So, type the file, filter with findstr, split records with for command using the spaces as delimiters and read from script only the needed data.

Dim oShell
    Set oShell = WScript.CreateObject("WScript.Shell")

Dim strCommand
    strCommand = "cmd /q /c ""for /F ""tokens=7 delims= "" %f in ('type ..\data.txt ^| findstr /r ""[0-9]+ errors"" ') do echo %f """

Dim oData
    Set oData = oShell.Exec( strCommand )

Dim strData 
    strData = oData.StdOut.ReadAll()

Dim aData 
    aData = Split( strData, vbCrLf )

    WScript.Echo strData

Upvotes: 0

Ekkehard.Horner
Ekkehard.Horner

Reputation: 38775

The best way to get info from short structured files is to .ReadAll() the file into memory and to apply a regular expression that cuts the desired data from the string. In code:

  Option Explicit
  Dim goFS     : Set goFS = CreateObject( "Scripting.FileSystemObject" )
  Dim reCut : Set reCut = New RegExp
  reCut.Global = True
  reCut.Pattern = "(\d+) errors"
  Dim oMTS : Set oMTS = reCut.Execute(goFS.OpenTextFile("..\data\log.txt").ReadAll)
  Dim oMT
  For Each oMT IN oMTS
      WScript.Echo oMT.SubMatches(0)
  Next

output:

1563
1499

Upvotes: 2

Lee Brindley
Lee Brindley

Reputation: 6522

You could read each line backwards, detect that "error" is present then read from the following whitespace until the next whitespace.

Upvotes: 0

Related Questions