Wednesday, April 21, 2010

Script to create a file and add odd line to second file

Write a Script to create two text files and write some lines in the first file and copy the odd lines of the first file in to the second file.

Writing a VB Script using WriteLine and ReadLine Methods of FileSystemObject to generate the required result


'Script to create two text files,
'Write few lines into the first text file.
'Copy all the odd lines from the
'first text file to the second text file

'Create an object variable to interact with the File System Object
Set Fso = CreateObject("Scripting.FileSystemObject")

'Create Two text files using CreateTextFile method
Set fil = Fso.CreateTextFile("F:\Text1.txt")
Fso.CreateTextFile("F:\Text2.txt")

'Write few lines into the first text file
For i = 1 to 100
fil.WriteLine("This is Line "&i)
Next

Set fil = nothing

'Open first text file in read mode and second one in write mode
Set fil1 = fso.OpenTextFile("F:\Text1.txt",1, False)
Set fil2 = fso.OpenTextFile("F:\Text2.txt",2, False)

'Scan text file until we reach the endofstream
'Set the line number for every time scanned the file
'if the line number is odd copy in the second file
Do While Not fil1.AtEndOfStream
Line_number = fil1.line
If Line_number MOD 2 <> 0 Then
fil2.WriteLine(fil1.ReadLine)
Else
fil1.SkipLine
End If
Loop

Set fil = nothing
Set fil1=Nothing
Set fil2 = nothing

No comments:

Post a Comment