Find and replace a string in VBScript text

I am looking for VBScript that does a search and replace in files (e.g. 1.txt 2.xml). I have a file "1.txt", inside which is the word "temporary", and I want to change it to "permanent". Since I get this file a lot, I need a script for it.

Every time I try to write a script containing the open txt file and the replace command, this is not the case.

I found a script that changes this file with another file and performs the changes internally, but this is not what I am looking for.

+5
source share
2 answers

try it

If WScript.Arguments.Count <> 3 then
  WScript.Echo "usage: Find_And_replace.vbs filename word_to_find replace_with "
  WScript.Quit
end If

FindAndReplace WScript.Arguments.Item(0), WScript.Arguments.Item(1), WScript.Arguments.Item(2)
WScript.Echo "Operation Complete"

function FindAndReplace(strFilename, strFind, strReplace)
    Set inputFile = CreateObject("Scripting.FileSystemObject").OpenTextFile(strFilename, 1)
    strInputFile = inputFile.ReadAll
    inputFile.Close
    Set inputFile = Nothing
    Set outputFile = CreateObject("Scripting.FileSystemObject").OpenTextFile(strFilename,2,true)
    outputFile.Write Replace(strInputFile, strFind, strReplace)
    outputFile.Close
    Set outputFile = Nothing
end function 

Save this in a file called Find_And_Replace.vbs, then it can be used on the command line like this.

[C:\]> Find_And_Replace.vbs "C:\1.txt" "temporary" "permanent"

* "This"!= "This"

, , .

If WScript.Arguments.Count <> 3 then
  WScript.Echo "usage: Find_And_replace.vbs filename word_to_find replace_with "
  WScript.Quit
end If

FindAndReplace WScript.Arguments.Item(0), WScript.Arguments.Item(1), WScript.Arguments.Item(2)
WScript.Echo "Operation Complete"

function FindAndReplace(strFile, strFind, strReplace)
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set objInputFile = objFSO.OpenTextFile(strFile,1)
    strTempDir = objFSO.GetSpecialFolder(2)
    Set objTempFile = objFSO.OpenTextFile(strTempDir & "\temp.txt",2,true)
    do until objInputFile.AtEndOfStream
        objTempFile.WriteLine(Replace(objInputFile.ReadLine, strFind, strReplace))
    loop
    objInputFile.Close
    Set objInputFile = Nothing
    objTempFile.Close
    Set objTempFile = Nothing
    objFSO.DeleteFile strFile, true
    objFSO.MoveFile strTempDir & "\temp.txt", strFile
    Set objFSO = Nothing
end function 
+5

, :

Set objFS = CreateObject("Scripting.FileSystemObject")
strFile=WScript.Arguments.Item(0)
strOld=WScript.Arguments.Item(1)
strNew=WScript.Arguments.Item(2)
Set objFile = objFS.OpenTextFile(strFile)
Do Until objFile.AtEndOfStream
 strLine = objFile.ReadLine 
        if Instr(strLine,strOld)> 0 Then
          strLine=Replace(strLine,strOld,strNew)
        End If
 WScript.Echo strLine
Loop

:

c:\test> cscript //nologo find_replace.vbs file oldtext newtext
+1

All Articles