Read line to line txt file using VBS

I am trying this code:

filename = "test.txt" listFile = fso.OpenTextFile(filename).ReadAll listLines = Split(listFile, vbCrLf) For Each line In listLines WScript.Echo line 'My Stuff Next 

Or is it another:

 filename = "test.txt" Set fso = CreateObject("Scripting.FileSystemObject") Set f = fso.OpenTextFile(filename, ForReading) Do Until f.AtEndOfStream myLine = f.ReadLine WScript.Echo myLine 'My Stuff Loop 

Why in both cases, he repeats all the lines at once, and, of course, I can not work on a line? Any idea?

+6
source share
2 answers

Your file has funny EndOfLine markers. Suppose the lines end in vbLf:

 >> fn = "lf.txt" >> goFS.CreateTextFile(fn).Write Replace("abc ", " ", vbLf) >> set ts = goFS.OpenTextFile(fn) >> do until ts.AtEndOfStream >> WScript.Echo ts.ReadLine >> loop >> a b c 

As you can see, .ReadLine can handle vbLf (unix). However, your Split () on .ReadAll () will not execute:

 >> t = goFS.OpenTextFile(fn).ReadAll() >> a = Split(t, vbCrLf) >> WScript.Echo UBound(a) >> WScript.Echo a(0) >> 0 a b c 

t does not contain one vbCrLf, therefore Split () returns an array with UBound () == 0 containing t as its one element. Repeating this, at least 3 (4) lines will look. You can Split () on vbLf if you really need an array of strings.

But if your files contain the vbLf ending, then the .ReadLine loop should work fine.

.ReadLine () cannot handle vbCr (mac):

 >> fn = "cr.txt" >> goFS.CreateTextFile(fn).Write Replace("abc ", " ", vbCr) >> >> set ts = goFS.OpenTextFile(fn) >> do until ts.AtEndOfStream >> WScript.Echo ts.ReadLine >> loop >> c 

b + cr 'overwrites a + cr and then overwrites c + cr. The .ReadAll () approach will also fail if you do not use vbCr as a delimiter.

But if your files contain a vbCr ending, then none of your fragments can "echo all lines at once."

Does your file appear from space?

Update comment:

You cannot read UTF-8 using the Filesystemobject file . Either convert the file to UTF-16 and use the Unicode parameter of the format parameter when .OpenTextFile or work with the ADODB stream.

It would be interesting to know which EOL marker is used.

+8
source

Your code is working fine. I modified it a bit to show that the lines, in fact, are read alternately:

 Set fso=CreateObject("Scripting.FileSystemObject") filename = "test.txt" listFile = fso.OpenTextFile(filename).ReadAll listLines = Split(listFile, vbCrLf) i = 0 For Each line In listLines WScript.Echo CStr(i) + " : " + line i = i + 1 'My Stuff Next 

I assume fso is in your script somewhere, but I added that the extra line is just for completeness.

You must make sure that your input file does indeed have multiple lines separated by vbCrLf . Counter i helps debug every row when it shows the row index when reading rows.

+3
source

All Articles