how to read text file word by word in VB script? - vbscript

how to read text file word by word in VB script? please give all possible functions.

This:
Dim sAll : sAll = readAllFromFile("..\data\wbw.txt")
WScript.Echo sAll
WScript.Echo "-----------------------"
Dim oRE : Set oRE = New RegExp
oRE.Global = True
oRE.Pattern = "\w+"
Dim oMTS : Set oMTS = oRE.Execute(sAll)
Dim oMT
For Each oMT In oMTS
WScript.Echo oMT.Value
Next
Output:
===============================================================================
How to read text file word by word in VB script?
Please give all possible functions.
First, read the file line-by-line into an array. Then, when you're reading
through the array, parse each line word-by-word. As such:
-----------------------
How
to
read
text
file
word
by
word
in
VB
script
Please
give
all
possible
functions
First
read
the
file
line
by
line
into
an
array
Then
when
you
re
reading
through
the
array
parse
each
line
word
by
word
As
such
===============================================================================
avoids all the atrocities of Zomgie's solution:
Not usable with Option Explicit
Useless Dim of fixed array of no size
Useless array of lines
Costly ReDim Preserve with extra counter
Useless variable inputText
Split on " " makes "First," a word

First, read the file line-by-line into an array. Then, when you're reading through the array, parse each line word-by-word. As such:
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("c:\file.txt", ForReading)
Const ForReading = 1
Dim arrFileLines()
i = 0
Do Until objFile.AtEndOfStream
Redim Preserve arrFileLines(i)
arrFileLines(i) = objFile.ReadLine
i = i + 1
Loop
objFile.Close
For Each strLine in arrFileLines
inputText = strLine
outputArray = Split(inputText)
For Each x in outputArray
WScript.Echo "Word: " & x
Next
Next

Related

How to read every 20 lines from a text file using vbscript?

I have 180 lines in a text file and want to read every 20 lines (1-20, 21-40...)
Here is my current code:
Const ForReading = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile("C:\Bess_Automation\EditFiles\TSTVLD1.txt", ForReading)
'Reading the count of lines
objTextFile.ReadAll
strLinecount=objTextFile.Line
msgbox strLinecount
strnumoftimes=Round((strLinecount/20),0)
msgbox strnumoftimes
Here's how I'd approach the problem. This code sets the number of lines to be read at a time initially then opens the file for reading and sets up an array. While we're not finished reading the file, we add a line from it to myArray.
When we hit a multiple of 20 lines read, we report that and do whatever we need to with those 20 lines (in my case, I've just echoed them to the screen, separated by semicolons).
Then we reset the array to be empty again and repeat until all the file has been read, then output the final batch of lines (as otherwise they'd be ignored since we only do anything with batches of 20 in the example).
Option Explicit
Const LINES_TO_READ = 20
Dim iLines, iTotalLines
Dim oFso : Set oFso = CreateObject("Scripting.FileSystemObject")
Dim oFile : Set oFile = oFso.OpenTextFile("C:\temp\mytextfile.txt", 1)
Dim myArray()
ReDim myArray(0)
iLines = 0
iTotalLines = 0
While Not oFile.AtEndOfStream
myArray(UBound(myArray)) = oFile.ReadLine
iLines = iLines + 1
ReDim Preserve myArray(UBound(myArray)+1)
If iLines Mod LINES_TO_READ = 0 Then
WScript.Echo iLines & " read now."
' do anything you like with the elements of myArray here before we reset it to empty
WScript.Echo Join(myArray, ";")
' reset array to be totally empty again
ReDim myArray(0)
End If
Wend
WScript.Echo "Final Lines: " & Join(myArray, ";")
WScript.Echo "Total lines in file: " & iLines

Vbs script to add space if it finds a string like abc11adv to abc11 adv

Hi I am novice in vbs script. I have one text file every line has statements like
minis1in use by bla bla
rit34in use by someone
atp34in use by someone2
I want a vbs script to convert this text file to
minis1 in use by bla bla
rit34 in use by someone
atp34 in use by someone2
I found one vbs script but it replaces string at particular position in every line. But I want to search for a number only in first string in every line and number may be one digit or two digit or three digit after that number it should give space. Without replacing character with a space.
StrFileName = "C:\Users\Desktop\Scheduled\output.txt"
Const ForReading = 1
Const ForWriting = 2
Dim objFSO
Dim objTF
Dim objRexex
Dim StrFileName
Dim strTxt
StrFileName = "C:\Users\Desktop\Scheduled\output.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 = "^(.{6})[^-](.*)$"
strTxt = .Replace(strTxt, "$1" & " " & "$2")
End With
Set objTF = objFSO.OpenTextFile(StrFileName, ForWriting)
objTF.Write strTxt
objTF.Close
Maybe the pattern "^(\w+)(\d+)(\w+)" used non-globally will do what you want:
Option Explicit
Dim r : Set r = New RegExp
r.Global = False ' just the first
r.Pattern = "^(\w+)(\d+)(\w+)"
Dim s
For Each s In Split("minis1in use by+rit34adv use+atp34in use not34in use+not here1in use", "+")
WScript.Echo s
WScript.Echo r.Replace(s, "$1$2 $3")
WScript.Echo
Next
output:
cscript 25228592.vbs
minis1in use by
minis1 in use by
rit34adv use
rit34 adv use
atp34in use not34in use
atp34 in use not34in use
not here1in use
not here1in use
If "every line has statements like" what you've shown, and you're sure of that, make it easy on yourself:
strTxt = Replace(strTxt, "in use by ", " in use by ")

Insert "-" at a specific position using VBScript

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 '-'

ASP/VB Classic clear a line from a file

I have a file that looks like this:
Alpha,25,SomeBrand,Info
Gamma,2039,Crisps,Foobar
Epic,240,Win,Post
And I want to clear a certain line in this file, say line 2, so that it looks like this:
Alpha,25,SomeBrand,Info
Epic,240,Win,Post
How can I efficiently do this? This file has over 18000 lines, and I've tried reading in the complete file and writing back, but it was way too slow.
I don't know what is your file size but i've written a script (asp) is executed within 2.5 seconds.
Text file size is 35 million bytes and it has 35,000 lines.
Here:
<%#Language = VBScript %>
<%
Option Explicit
Dim oFso, oFile, arrLns, arrLNums, strOut, e
arrLNums = Array(15) '15th [and nnth] line(s) will be cleared
Set oFso = CreateObject("Scripting.FileSystemObject")
Set oFile = oFso.OpenTextFile("C:\old.txt", 1)
strOut = Replace(oFile.ReadAll(), vbCr, "")
arrLns = Split(strOut, vbLf)
For Each e In arrLNums : arrLns(e - 1) = "" : Next
strOut = Join(arrLns, vbCrLf)
oFso.CreateTextFile("C:\cleared.txt", True)_
.Write(strOut) 'Saved
oFile.Close
Set oFile = Nothing
Set oFso = Nothing
%>
As you can't use file pointer moving tricks to change the file 'on disk' in VBScript, you'll have to re-write it. Did you test whether using .ReadAll() and .Write is 'fast enough' for you? If yes, we could discuss a way to do the modifying efficiently. First question: Do you want to delete the offending line, or should it be replaced with an empty one?
Next Step:
This VBScript code:
Dim goFS : Set goFS = CreateObject( "Scripting.FileSystemObject" )
Dim sDir : sDir = "..\testdata\editlargefile"
Dim sSrcFSpec : sSrcFSpec = goFS.BuildPath( sDir, "lines.txt" )
Dim nLine : nLine = 5
Dim nSize : nSize = goFS.GetFile( sSrcFSpec ).Size
WScript.Echo nSize, "bytes in", sSrcFSpec
ReDim aHead( nLine - 2 )
Dim oTS, nIdx, sTail
Set oTS = goFS.OpenTextFile( sSrcFSpec )
For nidx = 0 To UBound( aHead )
aHead( nIdx ) = oTS.ReadLine()
Next
oTS.ReadLine
sTail = oTS.ReadAll()
oTS.Close
WScript.Echo Left( Join( aHead, vbCrLf ) & vbCrLf & vbCrLf & Left( sTail, 100 ), 150 )
Set oTS = goFS.CreateTextFile( sSrcFSpec, True )
oTS.Write Join( aHead, vbCrLf )
oTS.Write vbCrLf & vbCrLf
oTS.Write sTail
oTS.Close
output:
20888896 bytes in ..\testdata\editlargefile\lines.txt
This is line 1
This is line 2
This is line 3
This is line 4
This is line 6
This is line 7
This is line 8
This is line 9
This is line 10
Thi
=====================================================
xplfs.vbs: Erfolgreich beendet. (0) [11.42188 secs]
demonstrates the fastest VBScript way I can think of. The pseudo code
for a language able to do file pointer tricks would be
Open the file in read+write mode
Loop over the head lines to keep
If Delete
Skip line to delete
Reset write file pointer to end of previous line
Block write to file pointer till end
Else
Fill line to delete with spaces
End
Close the file
What language do you plan to use?

How to read from a text file using VBScript?

I am looking to see a simple way to read from and write to a text file using VBScript.
I think this is an acceptable method for writing to a file.
Dim f,
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.CreateTextFile("C:\test.txt", True, True)
f.WriteLine("Data to Add to file.")
f.Close
However, I would like to know how to read from a file in a similar fashion.
Use first the method OpenTextFile, and then...
either read the file at once with the method ReadAll:
Const ForReading = 1
Dim file, content
Set file = fso.OpenTextFile("C:\test.txt", ForReading)
content = file.ReadAll
or line by line with the method ReadLine:
Const ForReading = 1
Dim dict, file, row, line
Set dict = CreateObject("Scripting.Dictionary")
Set file = fso.OpenTextFile ("c:\test.txt", ForReading)
row = 0
Do Until file.AtEndOfStream
line = file.Readline
dict.Add row, line
row = row + 1
Loop
file.Close
'Loop over it
For Each line in dict.Items
WScript.Echo line
Next
Dim obj : Set obj = CreateObject("Scripting.FileSystemObject")
Dim outFile : Set outFile = obj.CreateTextFile("in.txt")
Dim inFile: Set inFile = obj.OpenTextFile("out.txt")
' Read file
Dim strRetVal : strRetVal = inFile.ReadAll
inFile.Close
' Write file
outFile.write (strRetVal)
outFile.Close

Resources