读一个单词并用特定的新字符串替换该单词的整个行

时间:2016-08-22 09:52:10

标签: vbscript

例如:code.vbs file1.txt "hello" "hello1"

这用hello1替换hello,而不用hello1替换hello的整行。

Option Explicit
Dim fso,strFilename,strSearch,strReplace,objFile,oldContent,newContent

strFilename = WScript.Arguments.Item(0)
strSearch   = WScript.Arguments.Item(1)
strReplace  = WScript.Arguments.Item(2)

'Does file exist?
Set fso = CreateObject("Scripting.FileSystemObject")
If fso.FileExists(strFilename) = False Then
   WScript.Echo "file not found!"
   WScript.Quit
End If

'Read file
Set objFile = fso.OpenTextFile(strFilename, 1)
oldContent = objFile.ReadAll

'Write file
newContent = Replace(oldContent, strSearch, strReplace, 1, -1, 0)
Set objFile = fso.OpenTextFile(strFilename, 2)
objFile.Write newContent
objFile.Close 

1 个答案:

答案 0 :(得分:2)

使用regular expression替换匹配整行:

Set re = New RegExp
re.Pattern    = ".*" & strSearch & ".*(\r?\n)"
re.IgnoreCase = False
re.Global     = True

newContent = re.Replace(oldContent, strReplace & "$1")