且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 VBscript 在 .txt 文件中查找和替换字符串

更新时间:2022-11-13 23:30:44

对.ReadAll()获取的文件内容使用Replace,并将结果写回.在代码中:

Use Replace on the file's content obtained by .ReadAll() and .Write the result back. In code:

Option Explicit

Dim goFS  : Set goFS  = Createobject("Scripting.FileSystemObject")
Dim goWAU : Set goWAU = WScript.Arguments.Unnamed

WScript.Quit main()

Function main()
  main = 1 ' assume error
  If 3 = goWAU.Count Then
     If goFS.FileExists(goWAU(0)) Then
        Dim s : s = goFS.OpenTextFile(goWAU(0)).ReadAll()
        If 0 < Instr(s, goWAU(1)) Then
           goFS.CreateTextFile(goWAU(0)).Write Replace(s, goWAU(1), goWAU(2))
           WScript.Echo "done"
           main = 0
        Else
           WScript.Echo goWAU(1), "not found"
        End If
     Else
        WScript.Echo goWAU(0), "does not exist"
     End If
  Else
     WScript.Echo "need 3 args: fspec, find, replacement"
  End If
End Function

输出:

copy con 28350055.csv
1,2,3
4,5,6
^Z

cscript 28350055.vbs 28350055.csv 5 4711
done

type 28350055.csv
1,2,3
4,4711,6

cscript 28350055.vbs 28350055.csv 5 4711
5 not found

cscript 28350055.vbs 28350055.cs 5 4711
28350055.cs does not exist

使用该演示来确定解决您的实际问题需要什么.

Use that demo to determine what is needed to solve your real world problem.