VBScript- (TIP) Perform simple math and change fields in a text file

Started by prehistory, April 10, 2009, 12:01:52 PM

Previous topic - Next topic

prehistory

Ok, here's another useful VBS solution for basic math in your text files.  Say you have a file that reads "measX measY measZ devX devY devZ", and what you WANT is a file where measZ is really the sum of measZ + devZ.  This is such simple math, but would take forever to calculated and write out in PW.  This script will take the original text file, split each line into its 6 fields (0-5), then update the 3rd field to be the sum of two of the fields, the write it out to a new file.

You can use the same script,with a couple modifications, to add, subtract, and do any math calculation on any field.  You can also pull the whole math part out and just use it to remove columns.


Const ForReading = 1
Const ForAppending = 2

GridFile = "D:\Data\piston_face_Files\user-data\xy_grid_error.txt"
Set objFSO = CreateObject("Scripting.FileSystemObject")

FiletoEdit = objFSO.GetFileName(GridFile)
FolderDest = Mid(objFSO.GetAbsolutePathName(GridFile),1,Len(objFSO.GetAbsolutePathName(GridFile))-(Len(FiletoEdit)))
set objTextFile = objFSO.OpenTextFile(GridFile)
fname = FolderDest & "xy_grid.txt"
Set objFile1 = objFSO.OpenTextFile(fname, ForAppending, True)
 
Do while NOT objTextFile.AtEndOfStream
'  arrStr is now an array that has each of your fields
' process them, whatever.....
  arrStr = split(objTextFile.ReadLine," ")
  arrX = CDbl(arrStr(0))
  arrY = CDbl(arrStr(1))
  arrZ = CDbl((arrStr(2)) + CDbl(arrStr(5)))
  arrNewStr = CStr(arrStr(0) & " " & arrStr(1) & " " & arrZ)
  objFile1.WriteLine arrNewStr
Loop