WinBatch Tech Support Home

Database Search

If you can't find the information using the categories below, post a question over in our WinBatch Tech Support Forum.

TechHome

Functions

Can't find the information you are looking for here? Then leave a message over on our WinBatch Tech Support Forum.

How to Use FileRead Example

Keywords: FileRead example needs additional asterisk

FileRead Line by Line. Generic Example:

    
handleread = FileOpen("c:\temp\sample.txt", "read")
linecount = 1
while 1
   line = FileRead( handleread ) 
   if line == "*EOF*"  then break
   Pause("Line: ":linecount, line)
   linecount = linecount + 1
endwhile  
FileClose(handleread)

ArrayFileGet Line by Line. Generic Example:

filename = "c:\temp\sample.txt"
arrFile = ArrayFileGet (filename , "" , 0)
linecount = ArrInfo(arrFile,6)
For x = 0 to linecount-1
  line =  arrFile[x]
  Pause("Line: ":x, line)
Next

FileRead and FileWrite. Generic Example:

The following is an example of how to use the FileRead function to read a file and make changes to it.

Say you had a file with the following contents ...

        ; this is sample.txt
        "SLIDEMAST1",08/20/9615:37,380,144,441,93,791,72,41,22154,22154,22154
        "SLIDEMAST1" ,08/20/9615:37,16,72,93,380,144,441,93,791,72,41,22154
... and you want to remove the quotes and spaces, and separate the date and time with a space.
The following WinBatch script shows how to accomplish this:
;====================snip==========================
        handleread=fileopen("sample.txt", "read")
        handlewrite=fileopen("sample22.txt", "write")
                      
        while 1
  
        line=FileRead(handleread) 
        if line == "*EOF*"  then break
           len=strlen(line)
           line=strreplace(line, " ", "")
           line=strreplace(line, '"SLIDEMAST1"', 'SLIDEMAST1') ;replace quotes with nothing        
           line=strreplace(line, "/", " ")      ;replace slash with space  
        filewrite(handlewrite, line)
        endwhile  

        fileclose(handleread)
        fileclose(handlewrite)
;====================snip==========================

Note Typo in WIL manual:

The FileRead example in the book (version 5.0) needs an additional asterisk.

Example:

;====================snip==========================
        handle = FileOpen("autoexec.bat", "READ")
        line=""
                while  line != "*EOF"
                        line = FileRead(handle)
                endwhile
;====================snip==========================
Add an asterisk into the While line on the other side of "*EOF". The following line is correct:

        while  line != "*EOF*"

NOTE that FileRead can only read alphanumeric characters in a file; it cannot read hex characters.

FileRead Example #2. How to Change Line Feeds to Carriage Return/Line Feeds:

;====================snip==========================
        handleread=fileopen("comments.txt", "read")
        handlewrite=fileopen("newcomments.txt", "write")
                      
        while 1
  
        line=FileRead(handleread) 
        if line == "*EOF*"  then break

           line=strreplace(line, @lf, @crlf)
           filewrite(handlewrite, line)
        endwhile  

        fileclose(handleread)
        fileclose(handlewrite)
;====================snip==========================

FileRead Example #3. How to Change One Line in a File:

Question:

I have a 10k or larger text file that I have been trying to extract just 1 line every 2-7 lines. The target line has a delimiter or a key word that can be searched for. I only want to print that line to a file. How is this done?

Is there a sample that demonstrates how to do this? At the present time I am removing all lines one at a time except the target line which takes too long. There must be a better method.

Answer:

OK. We'll try one last shot at the easy way, and if is is still tooooo slow, then we'll haul out the big guns.
;====================snip==========================
        fnamein="c:\temp\sourcefile.txt"
        fnameout="C:\temp\printfile.txt"

        inny=FileOpen(fnamein,"READ")
        outy=FileOpen(fnameout,"WRITE")

        keyword="Snozzle"

        while 1
           line=FileRead(inny)
           if line=="*EOF*" then break
           if strindexnc(line,keyword,0,@fwdscan)==0 then continue
        FileWrite(outy,line)
        endwhile

        FileClose(inny)
        FileClose(outy)
        Message("All Done. Print file in",fnameout)
;====================snip==========================

FileRead Example #4: How to Extract a Subset of Lines from a File:

In this example, we'll go down to line containing "c:\winnt\fw\conf\objects.c" and copy lines after all the way to a line in the file containing dashes "-------------".
; Select file in which information needs to picked out.
Types="All Files|*.*|WIL Files| *.wbt;*.mnu|Text Files|*.txt|"
fw1=AskFileName("Select FireWall-1 FWinfo Text File", "C:\", Types, "", 1)
Message("File selected was", fw1)

; go down to line containing "c:\winnt\fw\conf\objects.c"
; Copy line after all the way to the line with dashes ;"-------------".

beginning = "C:\WINNT\fw\conf\objects.c"

objfile=FileOpen(fw1, "READ")
outfile=FileOpen("c:\winnt\fw\objects.c","WRITE")

found=0

while 1
   line=FileRead(objfile)
   if line=="*EOF*" then break
   if found==0
      if strindexnc(line,beginning,0,@fwdscan)!=0
          found=1
          FileWrite(outfile,line) ; may not want this line
      endif
   else
      FileWrite(outfile,line)
      if strindex(line,"-------------",0,@fwdscan)!=0
          found=0
      endif
   endif

endwhile

FileClose(objfile)
FileClose(outfile)

FileRead Example #5: How to Find a Character, and Then Save Everything Thereafter in a File:


        keyword="Snozzola"

        fnamein="c:\temp\sourcefile.txt"
        fnameout="C:\temp\fixedfile.txt"

        inny=FileOpen(fnamein,"READ")
        outy=FileOpen(fnameout,"WRITE")

        while 1
           line=FileRead(inny)
           foundit=0
           if line=="*EOF*" then break
           mychar=StrSub( line, 1, 1 )
           if mychar == keyword then foundit=1
           if foundit==1 then FileWrite(outy,line)
        endwhile

        FileClose(inny)
        FileClose(outy)
        Message("All Done. Fixed file in",fnameout)

FileRead Example #6: How to Check if Line Matches Previous

Question:

I use the while statement to do the fileRead, use itemextract to extract text from each line. Then I compare this new line with the previous line to see if they are the same. What I want to do is start a counter, when there one of the line is the same, i want to set count = 1 and if the third line is also the same as first and second line, i want the count to go up to 2, and so on. But when it doesn't find any more repetition i want to get the count back to zero. what should i do?

Answer:

ummm I guessing here. good luck.
oldline3="sdsdsdsdsdsds" ;garbage
oldline2="ssdfdftewss" ; different garbage

while 1
   line=FileRead(handle)
   if line=="*EOF*" then break
   count=0
   if line==oldline2
      count=count+1
      if line==oldline3
         count=count+1
      endif
   endif
   Message("Count is",count")
   oldline3=oldline2
   oldline2=line
endwhile

FileRead Example #7: How to Delete a Blank Line

Question:

I need to open a file and delete the first line, which happens to be a blank line Thanks

Answer:

How big is the file? Is it a standard text file?

Slightly modified filecopy example from help file should do it for standard text files. If the file is REAL BIG it might take a while.

; the hard way to copy an ASCII file
testfile1=FileLocate("win.ini")
testfile2=strcat(FilePath(testfile1),"winini.bak")
old = FileOpen(testfile1, "READ")
new = FileOpen(testfile2, "WRITE")
x=FileRead(old) ; discard first line
while @TRUE             ; Loop till break do us end
        x = FileRead(old)
        If x == "*EOF*" Then Break
        FileWrite(new, x)
endwhile
FileClose(new)
FileClose(old)
Message("FileClose",strcat(testfile1,@crlf,"backed up to",@crlf,testfile2))

FileRead Example #8: How to Extract Out a Couple of Lines

Question:

How do I extract out a couple of lines from my file?

Answer:

	fnamein="c:\temp\infile.txt"
	fnameout="C:\temp\outfile.txt"

	inny=FileOpen(fnamein,"READ")
	outy=FileOpen(fnameout,"WRITE")

	keyword1="Description"
	keyword2="IP Address"

	while 1
		line=FileRead(inny)
		if line=="*EOF*" then break
			a=strindexnc(line,keyword1,0,@fwdscan) 
			b=strindexnc(line,keyword2,0,@fwdscan) 
			if a!=0
				FileWrite(outy,line)
			else
				if b!=0 
					FileWrite(outy,line)
				else
					continue
				endif
		endif

	endwhile		  
	FileClose(inny)
	FileClose(outy)
	

FileRead Example #9. Read the whole file and save the last line:

If the file is not too big it works well, other wise you are into BinaryBuffer territory. How big is the file.

The easy way...

fn="C:\someplace\logfile.txt"
fnout="C:\someplace\logfileout.txt"

line=""
handlewrite=FileOpen(fnout,"WRITE")
handle=FileOpen(fn,"READ")

        while 1
                lastline=line
                line=FileRead(handle)
                if line=="*EOF*" then break
        endwhile

FileWrite(handlewrite,lastline)

FileClose(handlewrite)
FileClose(handle)
Message("LastLine",lastline)

FileRead Example #10: Read Delimited File and Write out Matching Lines:

ZINFILE.TXT:
junk,d,activ,recfees
junk,d,activ,orcpin
junk,l,actup,orcpin
junk,apples,oranges,grapefruit

WB Code:
        fnamein="c:\temp\zinfile.txt"
        fnameout="C:\temp\zoutfile.txt"

        inny=FileOpen(fnamein,"READ")
        outy=FileOpen(fnameout,"WRITE")

        ;keywords=cases below
        ; Set the variable "editor", based on the pushbutton that was pressed


        while 1
           line=FileRead(inny)
           if line=="*EOF*" then break

           item2=ItemExtract(2,line,",")
           item3=ItemExtract(3,line,",")
           item4=ItemExtract(4,line,",")
           lineval=strcat(item2,",",item3,",",item4)

           gosub myswitch

 
        endwhile

        :myswitch
           For i=1 to 4 ;this will be the number of cases you have

           Switch i
              case 1
                if line=="*EOF*" then break
                keywords1 = "d,activ,recfees"
                if lineval==keywords1
                   FileWrite(outy,strcat(line,",","121-205002"))
                endif
                i=2
                ;break
              case 2
                if line=="*EOF*" then break
                keywords2 = "d,activ,orcpin"
                if lineval==keywords2
                   FileWrite(outy,strcat(line,",","121-205003"))
                endif
                i=3
                ;break
              case 3
                if line=="*EOF*" then break
                keywords3 = "l,actup,orcpin"
                if lineval==keywords3
                   FileWrite(outy,strcat(line,",","121-205004"))
                endif
                i=4
                ;break
              case 4
                 if line=="*EOF*" then break
                 if lineval != keywords1 &&  lineval != keywords2 && lineval != keywords3
                    FileWrite(outy,line)
                 endif
           endswitch

           Next

           Return

        FileClose(inny)
        FileClose(outy)
        Message("All Done. Output file in",fnameout)



FileRead Example #11: Read 3 Files and Check for Existence of Keyword (Found in File 1) in Files 2 and 3:


   BoxOpen("File Finder", "Initiating...")

        Ahandle=fileopen("FILEA.DAT", "read")


        Dhandle=fileopen("FILES.LOG", "write")
                      
        while @true
  
        Aline=FileRead(Ahandle) 
        if Aline == "*EOF*"  then break

        Afilename=ItemExtract(1,Aline,",")

           Bhandle=fileopen("FILEB.DAT", "read")
           while @true
               Bline=FileRead(Bhandle) 
               if Bline == "*EOF*"  then break
               Bfilename=ItemExtract(1,Bline,",")

               if Bfilename == Afilename
                  BoxTitle(Afilename)
                  BoxText(Bfilename)
                  Message("File Finder", "File Found")  ;TURN ON FOR DEBUGGING
               else
                  BoxTitle(Afilename)
                  BoxText(Bfilename)
                  Message("File Finder", "File Not Found") ;TURN ON FOR DEBUGGING
               endif
	     
           endwhile
           fileclose(Bhandle)


           Chandle=fileopen("FILEC.DAT", "read")
           while @true

              Cline=FileRead(Chandle) 
              if Cline == "*EOF*"  then break
                 Cfilename=ItemExtract(1,Cline,",")
	
                 if Cfilename == Afilename
                    BoxTitle(Afilename)
                    BoxText(Cfilename)
                    Message("File Finder", "File Found")  ;TURN ON FOR DEBUGGING
                 else
                    BoxTitle(Afilename)
                    BoxText(Cfilename)
                    Message("File Finder", "File Not Found") ;TURN ON FOR DEBUGGING
                endif
          endwhile
              fileclose(Chandle)
        endwhile

        fileclose(Ahandle)


        fileclose(Dhandle)




Example #12: Extract out Part of a Line

Question:

I have a large file i need to clean up. There are 2 spots that i need to edit as follows

The first script needs to search for this text EXIT! - then delete that entire line.

The second script deals with e-mail addresses We can search for the @ symbol then edit each line as follows

21 0:11:27 1997: joesmith@smith.com redeemed 3425678 
Delete all text prior to the e-mail address and delete all text after the e-mail address then move on to the next line.

Note: the pre and post text is different on every line.

Answer:


infile="c:\incoming\aaaa.txt"
outfile="c:\incoming\bbbb.txt"

inny=FileOpen(infile,"READ")
outy=FileOpen(outfile,"WRITE")
count=0
BoxOpen(count,"initializing")

while 1
line=FileRead(inny)
if line=="*EOF*" then break
if strindexNC(line,"exit!",0,@fwdscan)!=0 then continue
ptr=strindex(line,"@",0,@fwdscan)
if ptr==0 then continue
prevptr=strindex(line," ",ptr,@backscan)+1
nextptr=strindex(line," ",ptr,@fwdscan)-1
email=StrSub(line,prevptr,nextptr-prevptr+1)
count=count+1
boxtext(email)
BoxTitle(count)
FileWrite(outy,email)
endwhile

FileClose(inny)
FileClose(outy)
Message("All","Done")

Check for a blank line and delete it:

a=FileOpen("C:\Temp\filein.txt","READ")
b=FileOpen("C:\Temp\fileout.txt","WRITE")

while 1
	line=FileRead(a)
	if line=="*EOF*" then break
	if line=="" then continue
	FileWrite(b,line)
endwhile
FileClose(a)
FileClose(b)

Article ID:   W13073
Filename:   FileRead Examples.txt
File Created: 2013:04:19:08:28:18
Last Updated: 2013:04:19:08:28:18