I have a CSV with data like below
"01","567 "," ","This is a message"
I need to delete the trailing spaces and spaces in blank fields, while leaving the spaces in between data.
My code:
Dim inStream : Set inStream...
With inStream
.open
.type = 2
.charset = "utf-8"
.loadfromfile src
Dim outStream : Set outStream...
outStream.open
outStream.type = 2
While Not .EOS
arrLine = split(.read, ",")
strLine = trim(arrLine(0))
If ubound(arrLine) > 0 Then
For intField = 1 To ubound(arrLine)
strLine = strLine & "," & trim(arrLine(intField))
Next
End If
outStream.write(strLine)
outStream.savetofile dest, create
WEnd
outStream.close
.close
End With
You can split your CSV line into an array and then loop through and use the 'Trim' function on each item.
There are surprisingly good vbscript examples like this on google.
Related
I am trying to read cyrillic values separated by ; from a file, scan every line for match in the first value and assign the following values to variables.
Here is the code I have so far:
Dim objStream, strData, splitted
Set objStream = CreateObject("ADODB.Stream")
objStream.CharSet = "utf-8"
objStream.Open
objStream.LoadFromFile("C:\temp\textfile.txt")
strData = objStream.ReadText()
MsgBox strData
splitted = split(strData, ";")
textfile.txt contains something like this:
Име;Адрес;Телефон;
Име2;Адрес2;Телефон2;
I will have a variable like this:
searchFor = "Име"
and the script must assign Адрес and Телефон to variables.
Basically, I need to search for the name(Име or Име2) in every line from the textfile and then assign the second and the third values of that line to variables.
Currently strData gets the data but it's stored as a string that I cannot manipulate or don't know how.
First split the text at newlines, then split each line at semicolons, then check if the first field matches your search value. Example:
searchFor = "Име"
For Each line In Split(strData, vbNewLine)
fields = split(line, ";")
If fields(0) = searchFor Then
varA = fields(1)
varB = fields(2)
End If
Next
Note that you must save the script in Unicode format, lest your search string be botched.
Here is the complete final working script (Thanks to Ansgar Wiechers!)
Dim objStream, strData, fields
Set objStream = CreateObject("ADODB.Stream")
objStream.CharSet = "utf-8"
objStream.Open
objStream.LoadFromFile("C:\temp\textfile.txt")
strData = objStream.ReadText()
MsgBox strData
searchFor = "Име"
MsgBox searchFor
For Each line In Split(strData, vbNewLine)
fields = Split(line, ";")
If fields(0) = searchFor Then
varA = fields(1)
varB = fields(2)
End If
Next
I have text files that are approximately 6MB in size. There are some lines that contain the NULL (Chr(0))character that I would like to remove.
I have two methods to do this: using Asc()=0 but this takes approximately 50s to complete, the other method uses InStr (line, Chr(0)) =0 (fast ~ 4sec)but the results remove vital info from the lines which contain the NULL characters.
First line of text file as example:
##MMCIBN.000NULL7NULL076059NULL7653NULL1375686349NULL2528NULL780608NULL10700NULL\NULL_NC_ACT.DIR\CFG_RESET.INI
First method (works but VERY slow)
function normalise (textFile )
Set fso = CreateObject("Scripting.FileSystemObject")
writeTo = fso.BuildPath(tempFolder, saveTo & ("\Output.arc"))
Set objOutFile = fso.CreateTextFile(writeTo)
Set objFile = fso.OpenTextFile(textFile,1)
Do Until objFile.AtEndOfStream
strCharacters = objFile.Read(1)
If Asc(strCharacters) = 0 Then
objOutFile.Write ""
nul = true
Else
if nul = true then
objOutFile.Write(VbLf & strCharacters)
else
objOutFile.Write(strCharacters)
end if
nul = false
End If
Loop
objOutFile.close
end function
The output looks like this:
##MMCIBN.000
7
076059
7653
1375686349
2528
780608
10700
\
_NC_ACT.DIR\CFG_RESET.INI
Second method code:
filename = WScript.Arguments(0)
Set fso = CreateObject("Scripting.FileSystemObject")
sDate = Year(Now()) & Right("0" & Month(now()), 2) & Right("00" & Day(Now()), 2)
file = fso.BuildPath(fso.GetFile(filename).ParentFolder.Path, saveTo & "Output " & sDate & ".arc")
Set objOutFile = fso.CreateTextFile(file)
Set f = fso.OpenTextFile(filename)
Do Until f.AtEndOfStream
line = f.ReadLine
If (InStr(line, Chr(0)) > 0) Then
line = Left(line, InStr(line, Chr(0)) - 1) & Right(line, InStr(line, Chr(0)) + 1)
end if
objOutFile.WriteLine line
Loop
f.Close
but then the output is:
##MMCIBN.000\CFG_RESET.INI
Can someone please guide me how to remove the NULLS quickly without losing information. I have thought to try and use the second method to scan for which line numbers need updating and then feed this to the first method to try and speed things up, but quite honestly I have no idea where to even start doing this!
Thanks in advance...
It looks like the first method is just replacing each NULL with a newline. If that's all you need, you can just do this:
Updated:
OK, sounds like you need to replace each set of NULLs with a newline. Let's try this instead:
strText = fso.OpenTextFile(textFile, 1).ReadAll()
With New RegExp
.Pattern = "\x00+"
.Global = True
strText = .Replace(strText, vbCrLf)
End With
objOutFile.Write strText
Update 2:
I think the Read/ReadAll methods of the TextStream class are having trouble dealing with the mix of text and binary data. Let's use an ADO Stream object to read the data instead.
' Read the "text" file using a Stream object...
Const adTypeText = 2
With CreateObject("ADODB.Stream")
.Type = adTypeText
.Open
.LoadFromFile textFile
.Charset = "us-ascii"
strText = .ReadText()
End With
' Now do our regex replacement...
With New RegExp
.Pattern = "\x00+"
.Global = True
strText = .Replace(strText, vbCrLf)
End With
' Now write using a standard TextStream...
With fso.CreateTextFile(file)
.Write strText
.Close
End With
I tried this method (update2) for reading a MS-Access lock file (Null characters terminated strings in 64 byte records) and the ADODB.Stream didn't want to open an already in use file. So I changed that part to :
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFile(Lfile)
z = f.Size
set ts = f.OpenAsTextStream(ForReading, 0) 'TristateFalse
strLog = ts.Read(z)
ts.Close
set f = nothing
' replace 00 with spaces
With New RegExp
.Pattern = "\x00+"
.Global = True
strLog = .Replace(strLog, " ")
End With
' read MS-Access computername and username
for r = 1 to len(strLog) step 64
fnd = trim(mid(strLog,r, 32)) & ", " & trim(mid(strLog,r+32, 32)) & vbCrLf
strRpt = strRpt & fnd
next
I have a problem in that I need to read a specified quantity of characters from a text file, but the specified quantity varies so I cannot use a constant EG:
variable = WhateverIsSpecified
strText = objFile.Read (variable) ' 1 ~ n+1
objOutfile.write strText
NOT
strText = objFile.Read (n) ' n = any constant (interger)
When using the first way, the output is blank (no characters in the output file)
Thanks in advance
UPDATE
These are the main snippets in a bit longer code
Set file1 = fso.OpenTextFile(file)
Do Until file1.AtEndOfStream
line = file1.ReadLine
If (Instr(line,"/_N_") =1) then
line0 = replace(line, "/", "%")
filename = file1.Readline
filename = Left(filename, len(filename)-3) & "arc"
Set objOutFile = fso.CreateTextFile(destfolder & "\" & filename)
For i = 1 to 5
line = file1.Readline
next
nBytes = line 'this line contains the quantity needed to be read eg 1234
Do until Instr(line,"\") > 0
line = file1.ReadLine
Loop
StrData = ObjFile.Read (nBytes)
objOutFile.Write StrData
objOutFile.close
End if
Loop
WScript.quit
My own stupid error,
StrData = ObjFile.Read (nBytes)
should be
StrData = file1.Read (nBytes)
I need to grab a log file from a URL and then print the log file line by line. I can successfully get the file this way:
Dim filePath,fileName
filePath = "http://localhost/osat/spawn_pi_logs"
fileName = "/Spawn.log"
FilePath = filePath & fileName
Set req = CreateObject("Msxml2.XMLHttp.6.0")
req.open "GET", FilePath, False
req.send
If req.Status = 200 Then
Response.Write "Found the file<br>"
Response.Write req.responsetext
End If
That code writes the text of my log file to the screen in one huge ugly blob. I want to walk through it, format it, search it, etc and write it out with code similar to this:
Do While Not TextStream.AtEndOfStream
Dim sLine
sLine = TextStream.readLine
sLine = sLine & "<br>"
Response.Write sLine
Loop
However, how do I convert my req object (which has a generic stream at req.ResponseStream) and convert it to a Text Stream?
You can save the response to a text file by incorporating an ADO Stream and writing the responseBody:
If req.Status = 200 Then
With CreateObject("ADODB.Stream")
.Type = 1 'adTypeBinary
.Open
.Write req.responseBody
.SaveToFile "c:\myfile.txt"
.Close
End With
End If
Then you can open your text file using OpenTextFile() and read it as a TextStream.
But, you could just split your responseText into an array with the Split() function and not worry about saving and reading a text file:
If req.Status = 200 Then
' Create a line array...
a = Split(req.responseText, vbCrLf)
For i = 0 To UBound(a)
' Process each line
Next
End If
Thank you PHD443322. This code works great:
a = Split(req.responsetext, vbCrLf)
for each x in a
response.write(x & "<br />")
next
The key was not only the Split command, but also using the VBScript vbCrLf constant to set the delimiter.
I have a file which has multiple lines.
It is required to have "-" after 8th position in every line.
I can read lines with "-" at 9th position, but I am not able to write "-" at the 9th position if it is not there.
Any help would be really appreciated.
You can't insert characters in a VBScript string, because these are immutable; you'll have to concatenate a new string from Left(sOrgStr, 8) & "-" & Mid( sOrgStr, 9). (The numbers are +-1 depending on how you count.)
This vbs will
open a file C:\temp\log.txt,
make a global change with a single regexo
write the new updated text back over the original file
Please change the path to your file to suit in this line
StrFileName = "C:\temp\log.txt"
Const ForReading = 1
Const ForWriting = 2
Dim objFSO
Dim objTF
Dim objRexex
Dim StrFileName
Dim strTxt
StrFileName = "C:\temp\log.txt"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTF = objFSO.OpenTextFile(StrFileName, ForReading)
Set objregex = CreateObject("vbscript.regexp")
strTxt = objTF.ReadAll
objTF.Close
With objregex
.Global = True
.MultiLine = True
.Pattern = "^(.{8})[^-](.*)$"
strTxt = .Replace(strTxt, "$1" & "-" & "$2")
End With
Set objTF = objFSO.OpenTextFile(StrFileName, ForWriting)
objTF.Write strTxt
objTF.Close
you can fix the strings you read using this code:
s="input string"
if (mid(s,9,1)<>"-") then 'the 9th character isn't "-"
s=left(s,8) & "-" & mid(s,9)
end if
I suggest you'll open your file for input and re-write it into another text file.
You could use regular expressions.
If you're reading the lines 1-by-1 I think you need something like
Set objRe = New RegExp
' this will match any line having 9 or more characters,
' where the 9-th character is not "-", and capture the first 8 characters in the group #1
objRe.Pattern = "^(.{8})[^-]"
' Open the file, read lines, in the inner loop, call:
line = objRe.Replace( line, "$1-" ) ' This will replace the RE with the group #1 followed by '-'