Link to home
Create AccountLog in
Avatar of bravotango
bravotango

asked on

vbs replace text

Hello Experts,
Once again I ask for help. Not even sure this is possible. The following script works OK and all instances of "LDEBIT" are replaced. However, I would like to replace all instances of "^" or CHR(94). I have tried both those and it doesn't work.

Dim pattern
Dim replacement
' We must define ForWriting because the
' imode constants are unknown to VBScript
Const ForWriting = 2
Const inF = "NewSavings.qif"
Const outF = "Testfile1.txt"

' Here are the strings for replacement.
pattern = "LDEBIT"
replacement = vbCRLF

Dim Text
Dim fso                 ' Object variable
Dim oFileIn, oFileOut   ' Text stream
Dim path, fileIn, fileOut

path = GetPath()        ' Retrieve current path to script.
fileIn = path & inF     ' Create filenames.
fileOut = path & outF

Set fso = CreateObject("Scripting.FileSystemObject")

If Not fso.FileExists(fileIn) Then  ' Input file exists?
    WScript.Echo "File '" & fileIn & "' not found"
    WScript.Quit 1
End If

' Input file present; open file and create output file.
Set oFileIn = fso.OpenTextFile(fileIn)   ' Open input file.
Set oFileOut = fso.OpenTextFile(fileOut, _
                    ForWriting, True)    ' Open output file.

Do While Not (oFileIn.atEndOfStream)
    Text = oFileIn.ReadLine              ' Read a line.
    Text = Filter(Text, pattern, replacement)
    oFileOut.WriteLine Text              ' Write text.
Loop

WScript.Echo "Text file: " & fileIn & vbCrLf & _
             "Written into: " & fileOut

Function GetPath
    ' Retrieve the script path.
    Dim path
    path = WScript.ScriptFullName  ' Script name
    GetPath = Left(path, InStrRev(path, "\"))
End Function

Function Filter(txt, expr1, expr2)
    ' Replace expr1 with expr2 in text.
    Dim oReg

    Set oReg = New RegExp        ' Create regular expression.
    oReg.Global = True           ' All matches
    oReg.IgnoreCase = True       ' Make case-insensitive.

    ' Replace all expr1 with expr2.
    oReg.Pattern = expr1          ' Set pattern.
    Filter = oReg.Replace(txt, expr2)
End Function

'*** End
ASKER CERTIFIED SOLUTION
Avatar of R_Rajesh
R_Rajesh

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
Avatar of bravotango
bravotango

ASKER

Hi R Rajesh. That works nicely many thanks. You have a good day too!!