bill
bill

Reputation: 771

Extract text string from file

I am writing a utility to collect all system information from all devices on a network to an XML document, and one of the values is a certain software version number. Unfortunately the version number is only stored in a single text file on each machine (c:\master.txt) the even more fun part is, each text file is formatted differently depending on the image that was used.

One could say

Product Number: 11dsSt2 BRANDONII,STNS6.0.2.200

The next

Ver: 22335TS BOX2 S6.1.3.011,STN

and so on.

What I did, is create a VBS that looks for a number pattern that matches the version pattern, which is

[A-Z]#.#.#.### 

This works, however I just want to output that pattern, not the entire line. Here is my code. Any Suggestions?

Const ForReading = 1
Set objRegEx = CreateObject("VBScript.RegExp")
objRegEx.Pattern = "[A-Z]{1}[0-9]{1}.[0-9]{1}.[0-9]{1}.[0-9]{3}"
objregex.global = true
objregex.ignorecase = true
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\master.txt", ForReading)
Do Until objFile.AtEndOfStream
strSearchString = objFile.ReadLine
set colMatches = objRegEx.Execute(strSearchString)
If colMatches.Count > 0 Then
Addmatch
End If

Loop
objFile.Close
Sub Addmatch 'Creates a text file with the part number
Const ForAppending = 8
Set objFSO = CreateObject("Scripting.FileSystemObject")
set objFile1 = objFSO.OpenTextFile("C:\test.txt", ForAppending, True)
objFile1.Writeline strSearchString 
objFile1.Close

end sub

Upvotes: 0

Views: 3340

Answers (2)

Ekkehard.Horner
Ekkehard.Horner

Reputation: 38745

Use the first/one and only match to obtain the value, and pass this to a slightly modified version of Addmatch:

If colMatches.Count > 0 Then
   Addmatch colMatches(0).Value
End If

...

Sub Addmatch(sWhatToWriteLn) ' some truthful comment
  Const ForAppending = 8
  Set objFSO = CreateObject("Scripting.FileSystemObject")
  Set objFile1 = objFSO.OpenTextFile("C:\test.txt", ForAppending, True)
  objFile1.Writeline sWhatToWriteLn

...

Upvotes: 1

Ken White
Ken White

Reputation: 125661

You're storing the entire line you read from the file (that you have in strSearchString) instead of just the matched text. Use something like this instead (untested!):

if ColMatches.Count > 0 then
  AddMatch(ColMatches(0))      ' Just grab the matched text and pass to AddMatch
End If

Sub AddMatch(strMatchedText)   ' Change to accept parameter of text to write out
  ' Other code
  objFile1.Writeline strMatchedText
  objFile1.Close
End Sub

Upvotes: 1

Related Questions