以下の私の例は洗練されていると思いますが、始めるのに十分であることを願っています.
私のデモ 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いくつかのメモを投稿するのを忘れていました。テストを簡単にするために、2 列目にダブル スペースを入れました。簡単に言うと、スクリプトの動作を確認するには、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