user3368883
user3368883

Reputation:

How to replace double quotes to a space in VBScript?

I need open the CSV file, replace the double quotes with space and save the new file with txt extension.

I have tried this VBScript code but the first file Output_D1.txt is empty, the Output_D2.txt file contains rows of the Output_D1.csv, the Output_D3.txt file contains rows of the Output_D2.csv... etc.

How to do resolve this ?

   nArr = Array("D1", "D2", "D3", "D4", "D5", "D6")   

   Set reP = new RegExp  
   reP.Pattern = "\"""     

   For I = 0 To UBound(nArr) 
      InFilename = "Output_" & nArr(I) & ".csv"
      Set FILE1 = CreateObject("scripting.FileSystemObject")
      Set infile = FILE1.OpenTextFile(InFileName, 1, False)   
      strg = reP.Replace(strg, " ")
      InFilenameNew = "Output_" & nArr(I) & ".txt"
      Set Outfile = File1.CreateTextFile(inFileNameNew, 1, False)
      Outfile.Write(strg) 
      strg = infile.ReadAll
      infile.Close  
   Next 

Upvotes: 0

Views: 412

Answers (1)

Captain_Planet
Captain_Planet

Reputation: 1336

Try this:

  • You need to set the RegExp global option to replace all occurences of quotes
  • You need the full path to the CSV files (see rootFolder for a hard-coded example)
  • ReadAll is used in the wrong place (it needed to be before the RegExp replace!)

    Option Explicit 
    
    dim fso : Set fso = CreateObject("Scripting.FileSystemObject")
    dim rootFolder : rootFolder = "C:\Temp\"
    dim nArr : nArr = Array("D1", "D2", "D3", "D4", "D5", "D6")   
    dim i, inFilename, inFilenameNew, infile, outfile, filecontent
    Const ForReading = 1, ForWriting = 2
    
    dim reP : Set reP = new RegExp 
    reP.Global = true
    reP.Pattern = "\"""     
    
    For i = 0 To UBound(nArr) 
        inFilename = rootFolder & "Output_" & nArr(i) & ".csv"
        inFilenameNew = rootFolder & "Output_" & nArr(i) & ".txt"   
    
        if (fso.FileExists(inFilename)) Then
            Set infile = fso.OpenTextFile(InFileName, ForReading) 
            filecontent = infile.ReadAll
            filecontent = reP.Replace(filecontent, " ")
            infile.Close
            Set infile = Nothing
    
            Set outfile = fso.CreateTextFile(inFileNameNew, True)
            outfile.Write(filecontent)
            outfile.Close  
            Set outfile = Nothing
        End If          
    Next 
    
    Set reP = Nothing
    Set fso = Nothing
    

Upvotes: 1

Related Questions