首页 > 解决方案 > 读取文本文件中的内容并使用 VBS 将其替换为另一个文本文件中的指定文本

问题描述

我一直在尝试创建一个 VBS 脚本来读取一个文本文件中的文本内容并将其替换为位于另一个文本文件中的指定文本。

我正在尝试获取以下脚本来读取名为 first.txt 的文件中的内容。一旦这样做,它就应该用从名为 first.txt 的文件中读取的内容替换名为 second.txt 的文件中的指定文本。这就是我到目前为止所拥有的。它替换了 second.txt 文件中的所有文本,而不是替换指定的文本。在我拔出最后一根头发之前有任何想法。谢谢!

Const ForReading = 1
Const ForWriting = 2
Set objFileToRead = CreateObject("Scripting.FileSystemObject").OpenTextFile("first.txt",1)
strFileText = objFileToRead.ReadAll()
objFileToRead.Close

strText = objFile.ReadAll
objFile.Close
strNewText = Replace(strText, "@sec", strFileText)

Set objFile = objFSO.OpenTextFile("second.txt", ForWriting)
objFile.WriteLine strNewText
objFile.Close

标签: replacevbscriptscriptingbasicadsutil.vbs

解决方案


嘿@GeertBellekens 你的权利,谢谢你提出这个问题。我正要纠正这个。这个先前的脚本似乎只从 first.txt 文件中读取了第二行,所以我对变量减速和按指定行读取文本进行了微小的更改。这是最终的工作脚本。它读取 first.txt 文件中的第一行文本并将其替换为位于 second.txt 文件中的“@sec”文本。请让我知道这对你有没有用。谢谢!!。

这是工作代码:

Option Explicit


Dim fso,strFilename,strSearch,strReplace,objFile,oldContent,newContent,strpw,objfso,strText,strNewText,filename,f,i,strline


filename = "first.txt"

Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile(filename)

For i = 1 to 0
    f.ReadLine
Next

strLine = f.ReadLine
Wscript.Echo strLine

f.Close





Const ForReading = 1
Const ForWriting = 2
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("second.txt", ForReading)

strText = objFile.ReadAll
objFile.Close
strNewText = Replace(strText, "@sec", strLine)

Set objFile = objFSO.OpenTextFile("second.txt", ForWriting)
objFile.WriteLine strNewText
objFile.Close

推荐阅读