我认为我下面的示例可以完善,但我希望它足以开始。
我的演示 CSV 文件“target.csv”:
column_name1,column_name2,column_name3
abc 123, dfr 1145 wse, ht6
axv 358, dgt 2245 ekl, x7r
amn 772, fxw 7633 foo, pmn
一个示例“whitespaceremover.vbs”:
Const ForReading = 1, ForWriting = 2
Dim fso, file, column
Set fso = CreateObject("Scripting.FileSystemObject")
With WScript.Arguments
If .Count <> 2 Then
WScript.Echo "Error: Needs to arguments."
WScript.Quit(-1)
End If
file = .Item(0)
column = .Item(1)
End With
If Not fso.FileExists(file) Then
WScript.Echo "Error: File " & UCase(file) & " not found."
WScript.Quit(-2)
End If
Dim csvFile, csvHeader, iColumn, idx
Set csvFile = fso.OpenTextFile(file, ForReading)
If Not csvFile.AtEndOfStream Then
csvHeader = Split(csvFile.ReadLine, ",", -1, 1)
Else
WScript.Echo "Error: File " & UCase(file) & " is empty."
csvFile.Close
WScript.Quit(-3)
End If
iColumn = -1
For idx = 0 To UBound(csvHeader)
If csvHeader(idx) = column Then
iColumn = idx
Exit For
End If
Next
If iColumn < 0 Then
WScript.Echo "Error: column " & UCase(column) & " not found."
csvFile.Close
WScript.Quit(-4)
End If
Dim csvFile2, arLine, strLine
Set csvFile2 = fso.OpenTextFile(file & ".csv", ForWriting, True)
csvFile2.WriteLine Join(csvHeader, ",")
Do Until csvFile.AtEndOfStream
strLine = Trim(csvFile.ReadLine)
arLine = Split(strLine, ",", -1, 1)
Do While InStr(1, arLine(iColumn), " ")
arLine(iColumn) = Replace(arLine(iColumn), " ", " ")
Loop
strLine = Join(arLine, ",")
csvFile2.WriteLine strLine
Loop
csvFile.Close
csvFile2.Close
Set csvFile = Nothing
Set csvFile2 = Nothing
Set fso = Nothing
结果(新文件“target.csv.csv”):
column_name1,column_name2,column_name3
abc 123, dfr 1145 wse, ht6
axv 358, dgt 2245 ekl, x7r
amn 772, fxw 7633 foo, pmn
PS一些我忘记发布的注释。为了测试简单,我在第二列放了双倍空格。很快,要查看实际使用的脚本column_name2
作为命令行参数,即:
Cscript whitespaceremover.vbs target.csv column_name2
编辑
在阅读了 Ansgar Wiechers 关于Replace
功能的评论后,我最终决定进行一些测试。与正则表达式相比,上面的代码可能很慢,但它可以工作。这是我的证明示例:
str1 = "1" & Space(2) & "2" & Space(4) & "3" _
& Space(1) & "4" & Space(6) & "5"
WScript.Echo "Original string: ", str1
Do While InStr(1, str1, " ")
str1 = Replace(str1, " ", " ")
Loop
WScript.Echo "New string: ", str1
'Result>>
'Original string: 1 2 3 4 5
'New string: 1 2 3 4 5