2016-08-22 54 views
-1

如:code.vbs file1.txt "hello" "hello1"读一个字,并用speceifed新的字符串替换字的整条生产线

这取代了招呼与hello1但hello1招呼不整行。

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 

回答

2

使用regular expression更换匹配一整行:

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

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

're.Global = TRUE;更换所有的Hello分组; 'strReplace = strReplace&vbCr'保留一个vbCrLf EOL标记。 –

+0

感谢您的帮助,但没有发生任何变化。文件保持不变。 – Charmendor

+0

@Charmendor然后你犯了一个错误。请编辑您的问题并显示您的更新代码。 –