Search code examples
stringtextvbscriptpseudocode

How to get a certain string in a text file


Here's an example text file named "sample.txt":

This is a sample text file and I need to return this string > "myScript.sql".
And this another string: "myNewScript.sql"
How do I do it using VBScript?

And what I want to do is to return the "myScript.sql" and "myNewScript.sql" string using VB Script.

Like:

If string's file extension =  ".sql"
  THEN
    myString = Scan left and get the string until the QUOTE (") symbol.
    Echo myString

Something like that.


Solution

  • You can easily use regular expressions in this case:

    Set objFSO = CreateObject("Scripting.FileSystemObject") 
    Set file = objFSO.OpenTextFile("sample.txt" , ForReading)  
    Const ForReading = 1
    
    Dim re
    Set re = new regexp 
    re.Pattern = """(\w+?[.]sql)"""
    re.IgnoreCase = True
    re.Global = True
    
    Dim line
    Do Until file.AtEndOfStream
        line = file.ReadLine
        For Each m In re.Execute(line)
           Wscript.Echo m.Submatches(0)
        Next
    Loop 
    

    By executing it with:

    cscript //nologo test.vbs
    

    With the file sample.txt:

    This is a sample text file and I need to return this string > "myScript.sql".
    And this another string: "myNewScript.sql"
    How do I do it using VBScript?
    

    You'll get this:

    myScript.sql
    myNewScript.sql