替换文本文件中的多个空格(VBS)

问题描述 投票:0回答:1

我通过替换字符来处理类似的文本文件,这些字符经常出现在文件中(多次出现),尤其是空格。 当我使用这个脚本时

set fso = CreateObject("Scripting.FileSystemObject")

soll1 = " "
soll2 = "<i>"
soll3 = "<b>"
ist1  = "  "  ' replacing two spaces by one space
ist2  = "//"
ist3  = "**"

Set readFile  = fso.OpenTextFile("Eingabe.txt",1,false)
set writefile = fso.CreateTextFile("Ausgabe.txt",2)

' Do until readfile.AtEndOfStream
' Do while not readfile.AtEndOfStream
  While not readfile.AtEndOfStream
    ThisLine = readfile.ReadLine
    If Instr(Soll1,ThisLine) Then   
    writefile.write Replace(ThisLine,ist2,soll2)
    writefile.write Replace(ThisLine,ist3,soll3)
    writefile.write Replace(ThisLine,"  "," ")  ' ist1/soll1
    Else
    writefile.write ThisLine & vbCrLf
    End If
Wend
' Loop

readfile.close
writefile.close

我在生成的名为“Ausgabe.txt”的文件中看到没有任何努力,没有替换两倍或三倍的空格。我做错了什么? 我还尝试了做直到...做而没有... 怎么了 ?请帮忙,谢谢,bedankt Uw

vbscript whitespace
1个回答
0
投票

要将给定字符(例如空格)的所有字符串减少为单个字符,您可以重复搜索和替换,直到找不到更多匹配项。这是一个例子:

Set oFSO = CreateObject("Scripting.FileSystemObject")
InFile = "Eingabe.txt"
OutFile = "Ausgabe.txt"

aSearch = Array("  ","//","**")
aReplace = Array(" ","<i>","<b>")

Contents = oFSO.OpenTextFile(InFile).ReadAll

For i = 0 To UBound(aSearch)
  Do While Instr(Contents,aSearch(i))>0
    Contents = Replace(Contents,aSearch(i),aReplace(i))
  Loop
Next

oFSO.CreateTextFile(OutFile,True).Write(Contents)

这是一次处理一行的变体(对于非常大的文件很有用):

Set oFSO = CreateObject("Scripting.FileSystemObject")
InFile = "Eingabe.txt"
OutFile = "Ausgabe.txt"

aSearch = Array("  ","//","**")
aReplace = Array(" ","<i>","<b>")

Set oInFile = oFSO.OpenTextFile(InFile)
Set oOutFile = oFSO.CreateTextFile(OutFile,True)

Do While Not oInFile.AtEndOfStream
  Line = oInFile.ReadLine
  For i = 0 To UBound(aSearch)
    Do While Instr(Line,aSearch(i))>0
      Line = Replace(Line,aSearch(i),aReplace(i))
    Loop
  Next
  oOutFile.WriteLine Line
Loop

oInFile.Close
oOutFile.Close
© www.soinside.com 2019 - 2024. All rights reserved.