Break down sections in a text file using vbscript - vbscript

I have a file which is in this format
name.css value
name.js value
I want to break this down and create strings which will be in this format
string1 = "c:\" + value + name + extension(css or js)
can someone please tell me how to do this in vbscript.
So far I am looking to break this into dictionary and then loop through and creating new dim objects which loops through the whole file and creates values but not getting it right.Any help is very much appreciated.
Thanks

Simple solution:
Set fso = CreateObject("Scripting.FileSystemObject")
Set re = New RegExp
re.Pattern = "\s+"
re.Global = True
Set f = fso.OpenTextFile("C:\your\input.txt")
Do Until f.AtEndOfStream
tokens = Split(Trim(re.Replace(f.ReadLine, " ")))
WScript.Echo "C:\" & tokens(1) & tokens(0)
Loop
f.Close

Related

subscript out of range error in vbscript

Can someone look at the below script and tell me why it's throwing this error subscript out of range error in vbscript ..In the text file there are two entries it writes to the file correctly but then it throws an error while exiting the loop so it never calls the other function..I think it's trying to run 3 times but there are just 2 entries in the text file
The text file is in this format
Format.css Shared
Design.css Shared
Dim strInputPath1
Dim txsInput1,txsOutput
Dim FSO
Dim Filename
Set FSO = CreateObject("Scripting.FileSystemObject")
strOutputPath = "C:\txt3.txt"
Set txsOutput = FSO.CreateTextFile(strOutputPath)
Set re = New RegExp
re.Pattern = "\s+"
re.Global = True
Set f = FSO.OpenTextFile("C:\Users\spadmin\Desktop\Main\combination.txt")
Do Until f.AtEndOfStream
tokens = Split(Trim(re.Replace(f.ReadLine, " ")))
extension = Split(tokens(0),".")
strInputPath1 = "C:\inetpub\wwwroot\Test\files\" & tokens(1) & "\" & extension(1) & "\" & tokens(0)
Set txsInput1 = FSO.OpenTextFile(strInputPath1, 1)
WScript.Echo strInputPath1
txsOutput.Writeline txsInput1.ReadAll
Loop
WScript.Echo "Calling"
txsInput1.Close
txsOutput.Close
f.Close
Call CreateCSSFile()
''''''''''''''''''''''''''''''''''''
' Merge Css Files
''''''''''''''''''''''''''''''''''''
Sub CreateCSSFile()
WScript.Echo "Called"
Dim FilenameCSS
Dim strInputPathCSS
Dim txsInputCSS,txsOutputCSS
Dim FSOCSS
Set FSOCSS = CreateObject("Scripting.FileSystemObject")
strOutputPathCSS = "C:\txt4.txt"
Set txsOutputCSS = FSOCSS.CreateTextFile(strOutputPath)
Set re = New RegExp
re.Pattern = "\s+"
re.Global = True
Set fCSS = FSOCSS.OpenTextFile("C:\Users\spadmin\Desktop\TestingTheWebService\combination.txt")
Do Until fCSS.AtEndOfStream
tokensCSS = Split(Trim(re.Replace(fCSS.ReadLine, " ")))
extensionCSS = Split(tokensCSS(0),".")
strInputPathCSS = "C:\inetpub\wwwroot\EpsShared\c\" & tokensCSS(1) & "\" & extensionCSS(1) & "\" & tokensCSS(0)
Set txsInputCSS = FSOCSS.OpenTextFile(strInputPathCSS, 1)
txsOutputCSS.Writeline txsInputCSS.ReadAll
Loop
fCSS.Close
txsInputCSS.Close
txsOutputCSS.Close
Set FSOCSS = Nothing
End Sub
If your file contains trailing blank lines, applying Split() may return arrays with less than 2 elements. In that case token(1) should throw a 'subscript out of range' error.
You should always check, if Split() workes as expected:
tokens = Split(Trim(re.Replace(f.ReadLine, " ")))
If 1 = UBound(tokens) Then
extension = Split(tokens(0),".")
If 1 = UBound(extension) Then
strInputPath1 = "..." & tokens(1) & "..."
Else
... parse error ...
End If
Else
... parse error or just trailing blank lines? ...
End If

Remove parts of a string and copy the rest back to a file with vbscript

I would like to remove the unwanted text from each string in a file.
the input string looks like this
username^time stamp^don't need this printed on printer name more useless info pages printed:some number
I want to remove everything else but keep the username,time stamp,printer name and some number.Then write each line to a file so the output looks like this
username timestamp printername some number
This is the code I'm working with
Set fs = CreateObject("Scripting.FileSystemObject")
sf = "C:\test.txt"
Set f = fs.OpenTextFile(sf, 1) ''1=for reading
s = f.ReadAll
segments = Split(s,"^",-1)
s= segments(1,)
f.Close
Set f = fs.OpenTextFile(sf, 2) ''2=ForWriting
f.Write s
f.Close
There's always a moment that somebody asks "Why not use a regular expression?". This is that moment.
Try this:
Dim re, s, match, matches
s = "Chuck Norris^12-12-2012^don't need this printed on HAL9000 more useless info pages printed:42 "
Set re = new regexp
re.pattern = "(.*)\^(.*)\^.*printed on (\w+).*pages printed:(\d+).*"
re.Global = True
Set matches = re.Execute(s)
Set match = matches(0)
msgbox "username=" & match.submatches(0)
msgbox "time stamp=" & match.submatches(1)
msgbox "printer=" & match.submatches(2)
msgbox "pages printed=" & match.submatches(3)
Neat huh? And I bet you'll figure out how to implement it in your existing code.
Code:
Const csSep = "^"
'username^time^(other arbitrary junk)^printer name^(other arbitrary junk)^page count
Dim sJunk : sJunk = "kurt^01:02:03^some junk^nec p7^nix^123"
WScript.Echo sJunk
Dim aParts : aParts = Split(sJunk, csSep)
Dim sNetto : sNetto = Join(Array(aParts(0),aParts(1),aParts(3),aParts(5)), csSep)
WScript.Echo sNetto
output:
kurt^01:02:03^some junk^nec p7^nix^123
kurt^01:02:03^nec p7^123

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

Read and write into a file using VBScript

How can we read and write some string into a text file using VBScript? I mean I have a text file which is already present so when I use this code below:-
Set fso = CreateObject("Scripting.FileSystemObject" )
Set file = fso.OpenTextFile("C:\New\maddy.txt",1,1)
This opens the file only for reading but I am unable to write anything
and when I use this code:-
Set fso = CreateObject("Scripting.FileSystemObject" )
Set file = fso.OpenTextFile("C:\New\maddy.txt",2,1)
I can just use this file for writing but unable to read anything. Is there anyway by which we can open the file for reading and writing by just calling the OpenTextFile method only once.
I am really new to VBScript. I am only familiar with C concepts.
Is there any link to really get me started with VBScript?
I guess I need to have a good knowledge of the objects and properties concepts.
You can create a temp file, then rename it back to original file:
Set objFS = CreateObject("Scripting.FileSystemObject")
strFile = "c:\test\file.txt"
strTemp = "c:\test\temp.txt"
Set objFile = objFS.GetFile(strFile)
Set objOutFile = objFS.CreateTextFile(strTemp,True)
Set ts = objFile.OpenAsTextStream(1,-2)
Do Until ts.AtEndOfStream
strLine = ts.ReadLine
' do something with strLine
objOutFile.Write(strLine)
Loop
objOutFile.Close
ts.Close
objFS.DeleteFile(strFile)
objFS.MoveFile strTemp,strFile
Usage is almost the same using OpenTextFile:
Set objFS = CreateObject("Scripting.FileSystemObject")
strFile = "c:\test\file.txt"
strTemp = "c:\test\temp.txt"
Set objFile = objFS.OpenTextFile(strFile)
Set objOutFile = objFS.CreateTextFile(strTemp,True)
Do Until objFile.AtEndOfStream
strLine = objFile.ReadLine
' do something with strLine
objOutFile.Write(strLine & "kndfffffff")
Loop
objOutFile.Close
objFile.Close
objFS.DeleteFile(strFile)
objFS.MoveFile strTemp,strFile
Find more about the FileSystemObject object at http://msdn.microsoft.com/en-us/library/aa242706(v=vs.60).aspx. For good VBScript, I recommend:
Option Explicit to help detect typos in variables.
Function and Sub to improve readilbity and reuse
Const so that well known constants are given names
Here's some code to read and write text to a text file:
Option Explicit
Const fsoForReading = 1
Const fsoForWriting = 2
Function LoadStringFromFile(filename)
Dim fso, f
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile(filename, fsoForReading)
LoadStringFromFile = f.ReadAll
f.Close
End Function
Sub SaveStringToFile(filename, text)
Dim fso, f
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile(filename, fsoForWriting)
f.Write text
f.Close
End Sub
SaveStringToFile "f.txt", "Hello World" & vbCrLf
MsgBox LoadStringFromFile("f.txt")
You could open two textstreams, one for reading
Set filestreamIn = CreateObject("Scripting.FileSystemObject").OpenTextFile("C:\Test.txt,1)
and one for appending
Set filestreamOUT = CreateObject("Scripting.FileSystemObject").OpenTextFile("C:\Test.txt,8,true)
The filestreamIN can read from the begining of the file, and the filestreamOUT can write to the end of the file.
Don't think so...you can only use openTextFile for reading (1), writing (2), or appending (8). Reference here.
If you were using VB6 instead of VBScript, you could do:
Open "Filename" [For Mode] [AccessRestriction] [LockType] As #FileNumber
Using the Random mode. For example:
Open "C:\New\maddy.txt" For Random As #1
You could put it in an Excel sheet, idk if it'll be worth it for you if its needed for other things but storing info in excel sheets is a lot nicer because you can easily read and write at the same time with the
'this gives you an excel app
oExcel = CreateObject("Excel.Application")
'this opens a work book of your choice, just set "Target" to a filepath
oBook = oExcel.Workbooks.Open(Target)
'how to read
set readVar = oExcel.Cell(1,1).value
'how to write
oExcel.Cell(1,2).value = writeVar
'Saves & Closes Book then ends excel
oBook.Save
oBook.Close
oExcel.Quit
sorry if this answer isnt helpful, first time writing an answer and just thought this might be a nicer way for you
You could also read the entire file in, and store it in an array
Set filestreamIN = CreateObject("Scripting.FileSystemObject").OpenTextFile("C:\Test.txt",1)
file = Split(filestreamIN.ReadAll(), vbCrLf)
filestreamIN.Close()
Set filestreamIN = Nothing
Manipulate the array in any way you choose, and then write the array back to the file.
Set filestreamOUT = CreateObject("Scripting.FileSystemObject").OpenTextFile("C:\Test.txt",2,true)
for i = LBound(file) to UBound(file)
filestreamOUT.WriteLine(file(i))
Next
filestreamOUT.Close()
Set filestreamOUT = Nothing
Regardless of what you're trying to do there should be no need to read to and write to a file at the same time. It would also use more memory which should always be avoided. I'd suggest reading the entire file using the .ReadAll method and then close it and do whatever you need to do with the data (assuming you read the contents into a variable) and then do a write to the same file and overwrite the file. If you're concerned with having something go wrong when over-writing the current file you could always try to write it to a different file and throw an error if that doesn't work before trying to over-write the original.
Below is some simple code to execute this:
sLocation = "D:\Excel-Fso.xls"
sTxtLocation = "D:\Excel-Fso.txt"
Set ObjExl = CreateObject("Excel.Application")
Set ObjWrkBk = ObjExl.Workbooks.Open(sLocation)
Set ObjWrkSht = ObjWrkBk.workSheets("Sheet1")
ObjExl.Visible = True
Set FSO = CreateObject("Scripting.FileSystemObject")
Set FSOFile = FSO.CreateTextFile (sTxtLocation)
sRowCnt = ObjWrkSht.usedRange.Rows.Count
sColCnt = ObjWrkSht.usedRange.Columns.Count
For iLoop = 1 to sRowCnt
For jLoop = 1 to sColCnt
FSOFile.Write(ObjExl.Cells(iLoop,jLoop).value) & vbtab
Next
Next
Set ObjWrkBk = Nothing
Set ObjWrkSht = Nothing
Set ObjExl = Nothing
Set FSO = Nothing
Set FSOFile = Nothing
This is for create a text file
For i = 1 to 10
createFile( i )
Next
Public Sub createFile(a)
Dim fso,MyFile
filePath = "C:\file_name" & a & ".txt"
Set fso = CreateObject("Scripting.FileSystemObject")
Set MyFile = fso.CreateTextFile(filePath)
MyFile.WriteLine("This is a separate file")
MyFile.close
End Sub
And this for read a text file
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
Set dict = CreateObject("Scripting.Dictionary")
Set file = fso.OpenTextFile ("test.txt", 1)
row = 0
Do Until file.AtEndOfStream
line = file.Readline
dict.Add row, line
row = row + 1
Loop
file.Close
For Each line in dict.Items
WScript.Echo line
WScript.Sleep 1000
Next

Need help removing ";" separator from items within an array, VBscript

My code is pulling from a data cells that lists multiple file paths and use semicolons " ; " as the separator. After spliting the data and placing it into an array, I need to remove the semicolons. otherwise my file paths are invalid when they enter the loop.
To clarify: My code works when there is only one file path in the data cell and dies once it hits a cell with multiple paths because of the ";"
ANY HELP would be much appreciated.
My code is the following:
<%
strValue = RS("ATTACHMENTS")
strAryWords = Split(strValue, ";")
' - strAryWords is now an array
For i = 0 to Ubound(strAryWords)
Set fso = Server.CreateObject("Scripting.FileSystemObject")
Set fileObject = fso.getFile(strAryWords(i))
Response.Write "<TH><TR align=left><TD>" & strAryWords(i) &" "& fileObject.Size &" "&"<img src=images/up.gif><BR></TD></TR>"
Set fileObject = Nothing
Set fso = Nothing
Next
%>
If the problem is strValue has a trailing ';', change your code to this:
strValue = RS("ATTACHMENTS")
strAryWords = Split(strValue, ";")
' - strAryWords is now an array
For i = 0 to Ubound(strAryWords)
If strAryWords(i) <> "" Then
Set fso = Server.CreateObject("Scripting.FileSystemObject")
Set fileObject = fso.getFile(strAryWords(i))
Response.Write "<TH><TR align=left><TD>" & strAryWords(i) &" "& fileObject.Size &" "&"<img src=images/up.gif><BR></TD></TR>"
Set fileObject = Nothing
Set fso = Nothing
End If
NEXT

Resources