In our routine as an administrator, we routinely work with text files. Let us try to understand how to work with them.
A usual logic would be
- Open the file, Loop line by line, display the contents (or process them)
Example 1:
In this example, we try to display the contents of the file that is passed as a parameter at the command line. I have not done validations and assume that a file name is already there. You can add three validations, first check if there is an argument. Second check if the file exists. Third check if it is a text file. I have a sample file called “sample.txt” in the same folder as the program.
Const ReadMode=1 set fso=CreateObject("Scripting.FileSystemObject") do until fstext.AtEndOfStream |
Let us check the output
C:\scripts\file-io>01-show-contents.vbs sample.txt //nologo C:\scripts\file-io> |
Let us make it more useful. At the end, let us say we want to display the total lines in this file.
Const ReadMode=1 do until fstext.AtEndOfStream |
C:\scripts\file-io>01-show-contents.vbs sample.txt //nologo C:\scripts\file-io> |
What if we needed the lines and words.
a. Use the split function, it splits a string and returns an array
b. use the ubound function to check how many elements are there in the array, and add 1
Const ReadMode=1 do until fstext.AtEndOfStream |
Sample Output of the same file
C:\scripts\file-io>01-show-contents.vbs sample.txt //nologo C:\scripts\file-io> |
Let us make it more complete. We do the following changes, we pass the parameter filename with a number, 1=show file, 2=show lines, 3=show words, 4=show all
Code
Const ReadMode=1 do until fstext.AtEndOfStream |
Various Runs
C:\scripts\file-io>01-show-contents.vbs sample.txt 1 //nologo C:\scripts\file-io>01-show-contents.vbs sample.txt 2 //nologo C:\scripts\file-io>01-show-contents.vbs sample.txt 3 //nologo C:\scripts\file-io>01-show-contents.vbs sample.txt 4 //nologo C:\scripts\file-io> |
No comments:
Post a Comment