Mr_Thomas
Mr_Thomas

Reputation: 869

VBscript replaces text but adds blank line

I have the following vbscript to replace text within a file. It does exactly what I want, however it adds a blank line at the end of the file for each pass I make. If I replace 'black' with 'red' and then change 'white' to 'yellow', it has added two blank lines to the end of the text file. Is there a way to change this so it doesn't add lines?

Here's the script:

Const ForReading = 1
Const ForWriting = 2

strFileName = Wscript.Arguments(0)
strOldText = Wscript.Arguments(1)
strNewText = Wscript.Arguments(2)

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(strFileName, ForReading)

strText = objFile.ReadAll
objFile.Close

strNewText = Replace(strText, strOldText, strNewText)

Set objFile = objFSO.OpenTextFile(strFileName, ForWriting)
objFile.WriteLine strNewText

objFile.Close

p.s. - the syntax is: cscript /nologo replace.vbs InputFile "OldText" "NewText"

Upvotes: 0

Views: 3178

Answers (3)

stark
stark

Reputation: 13189

Change

objFile.Writeline 

To

objFile.Write

Upvotes: 0

Ekkehard.Horner
Ekkehard.Horner

Reputation: 38745

Your

strText = objFile.ReadAll

will read all content of the file, including (possibly) a trailing EOL. (.ReadAll <> .ReadLine)

objFile.WriteLine strNewText

will add an EOL. So use

objFile.Write strNewText

Upvotes: 1

Paul Sullivan
Paul Sullivan

Reputation: 2875

objFile.WriteLine adds a newline character at the end. You probably need objFile.Write

WriteLine will add \r\n (or whatever the system newline is)

Upvotes: 2

Related Questions