Jump to content

This site uses cookies. By continuing to browse the site you are agreeing to our use of cookies. Find out more here. X
X


Photo

Need help to delete lines in a text file upon string match


Best Answer kylomas , 12 December 2013 - 12:13 AM

esahtar90,

 

As a new user it is beneficial to understand what went wrong with the code you are having a problem with. 

 

_FileWriteToLine expects a file name, you gave it a file handle.  So let's change you code as follows:

AutoIt         
#include <File.au3> ;-------------------------------------------------------------------------------- ; create test file filecopy(@scriptdir & '\testinputfile.txt',@scriptdir & '\testinputfile2.txt',1) ;-------------------------------------------------------------------------------- Global $count = 0 $file = @scriptdir & "\testinputfile2.txt" $po_number = FileReadLine($file, 1) $file_count = _FileCountLines($file) For $i = 1 To $file_count     $line = FileReadLine($file, $i)     If StringInStr($po_number, $line) > 0 Then         if _FileWriteToLine($file, $i, "", 1) <> 1 Then ConsoleWrite(@error & @LF) ; added an error check with console output         $count += 1     Else         ExitLoop     EndIf Next MsgBox(0, "Information:", "Count is " & $count & " PO number " & $po_number)

If you run this it will return "Count is 3 PO number is 3022".  The output file is left with two lines of 3022.  This is because you are deleting the line that matches your number with 

_FileWriteToLine($file, $i, "", 1)

 while using an increment variable to read the file line by line.

 

1ST read in loop - file has 5 lines = 3022 

2ND read in loop - file has 4 lines = 3022 and you start testing at line 2 skipping line 1 (which is 3022)

3RD read in loop - file has 3 lines = 3022 skipping line 1 and 2...

 

Not only is this a logical error but it is terribly inefficient (see HELP file doc for FileReadLine).

 

Let's say that we change the _FileWriteLine to

_FileWriteToLine($file, $i, "  ", 1)

to write a blank space rather than delete the line.

 

Now the message is "Count is 5 PO number is 3022" and there are 5 blank lines in the output file (as we expect).  Probably not what you want but logically correct. 

 

Given all of the above it is better to read the file to either a string or an array, process the string/array and write the file back from the string/array.

 

A couple of examples of this have been posted in previous replies.

 

I hope this helps.  Right now your best friend is the HELP file.

 

kylomas

 

edit: spelling

Go to the full post


  • Please log in to reply
7 replies to this topic

#1 esahtar90

esahtar90

    Seeker

  • Normal Members
  • 4 posts

Posted 11 December 2013 - 01:06 PM

Here is my code snippet, i have a text file testinputfile.txt, this file contains 10 numbers each repeated 5 time or less. I need my code to count every number in the file and the no. of occurence and upon match delete the file. however i'm not able to delete the lines upon string match ,

 

 

Kindly look the Code snippet and help me fix the bug,

 

 
#Include <File.au3>
 
Global $count = 0
$file = FileOpen("testinputfile.txt", 0)
$po_number = FileReadLine($file, 1)
$file_count = _FileCountLines("testinputfile.txt")
 
 
; Check if file opened for reading OK

If $file = -1 Then
    MsgBox(0, "Error", "Unable to open file.")
    Exit    
EndIf
 
For $i = 1 to $file_count
   $line = FileReadLine($file, $i)
   if StringInStr($po_number, $line) then
      _FileWriteToLine($file, $i, "", 1)
      $count += 1       
   Else
      ExitLoop   
   EndIf
   Next
   MsgBox(0, "Information:", "Count is " & $count & " PO number " & $po_number)

 

 

 

Thanks in advance.









#2 Melba23

Melba23

    I'm old - what's your excuse?

  • Moderators
  • 21,486 posts

Posted 11 December 2013 - 01:31 PM

esahtar90,

Welcome to the AutoIt forum. :)

Can we please have copy of this testinputfile.txt file and a better explanation of what you are trying to do. At the moment I am confused as to whether you want to delete the lines or the file itself. And what exactly is this "match" you speak of? Against what are you matching? Help us to help you by explaining clearly what you ar trying to achieve - you might understand perfectly, but we do not;)

M23
StringSize - Automatically size controls to fit text                                                               ExtMsgBox - A user customisable replacement for MsgBox
Toast - Small GUIs which pop out of the Systray                                                                Marquee - Scrolling tickertape GUIs
Scrollbars - Automatically sized scrollbars with a single command                                   GUIFrame - Subdivide GUIs into many adjustable frames
GUIExtender - Extend and retract multiple sections within a GUI                                      NoFocusLines - Remove the dotted focus lines from buttons, sliders, radios and checkboxes
ChooseFileFolder - Single and multiple selections from specified path tree structure      Notify - Small notifications on the edge of the display
Date_Time_Convert - Easily convert date/time formats, including the language               GUIListViewEx - Insert, delete, move, drag, sort and edit ListView items

#3 Xenobiologist

Xenobiologist

    Xx Code~Mega xX

  • MVPs
  • 4,850 posts

Posted 11 December 2013 - 01:43 PM

Use _FileReadToArray The a For Next loop and check every line.


Scripts & functions Organize Includes Let Scite organize the include files *new

Yahtzee The game "Yahtzee" (Kniffel, DiceLion)

LoginWrapper Secure scripts by adding a query (authentication)

_RunOnlyOnThis UDF Make sure that a script can only be executed on ... (Windows / HD / ...)

Internet-Café Server/Client Application Open CD, Start Browser, Lock remote client, etc.

MultipleFuncsWithOneHotkey Start different funcs by hitting one hotkey different times


#4 JLogan3o13

JLogan3o13

    115 and holding

  • MVPs
  • 4,182 posts

Posted 11 December 2013 - 01:44 PM

Edit:

 

Xenobiologist beat me to it. Look at this post for an example:

 

http://www.autoitscript.com/forum/topic/156858-help-delete-lines-from-text/#entry1135517


Edited by JLogan3o13, 11 December 2013 - 01:45 PM.

Have you ever listened to someone for a while and found yourself wondering..."Who ties your shoes for you?!"

 

My Scripts:Include Source with Compiled Script, Disk Maintenance for Windows XP, "Deal-A-Day" Sites, Windows Firewall UDF


#5 esahtar90

esahtar90

    Seeker

  • Normal Members
  • 4 posts

Posted 11 December 2013 - 01:47 PM

Hi Melba23,

 

The input file is attached,

 

It contains a list of numbers

e.g.

 

3025
3025
3026
3026
3026
3026
3026
3027
3027
3027

so on ...

 

My code should be able to pickup a number from the list (First line of the text file) and count the number of occurances,

now everytime it finds a match in the text file it should increment count and delete that particular line from the text file.

 

The whole code is function, everytime the fucntion gets called it returns the first numbers of the text file and number along with the number of occurance.

 

Many thanks :-)

Attached Files



#6 JLogan3o13

JLogan3o13

    115 and holding

  • MVPs
  • 4,182 posts

Posted 11 December 2013 - 01:55 PM

So you could do something like this:

#include <Array.au3> #include <File.au3> Local $aArray, $aTemp[1], $file, $text, $output, $x = 0 $file = @DesktopDir & "\testinputfile.txt" $output = @DesktopDir & "\output.txt" $text = "3026" _FileReadToArray($file, $aArray)     For $i = 1 To $aArray[0]         If StringInStr($aArray[$i], $text) Then             _ArrayAdd($aTemp, $aArray[$i])             $x += 1         EndIf     Next $aTemp[0] = $x _FileWriteFromArray($output, $aTemp)

Have you ever listened to someone for a while and found yourself wondering..."Who ties your shoes for you?!"

 

My Scripts:Include Source with Compiled Script, Disk Maintenance for Windows XP, "Deal-A-Day" Sites, Windows Firewall UDF


#7 kylomas

kylomas

    FUBAR

  • MVPs
  • 2,993 posts

Posted 12 December 2013 - 12:13 AM   Best Answer

esahtar90,

 

As a new user it is beneficial to understand what went wrong with the code you are having a problem with. 

 

_FileWriteToLine expects a file name, you gave it a file handle.  So let's change you code as follows:

AutoIt         
#include <File.au3> ;-------------------------------------------------------------------------------- ; create test file filecopy(@scriptdir & '\testinputfile.txt',@scriptdir & '\testinputfile2.txt',1) ;-------------------------------------------------------------------------------- Global $count = 0 $file = @scriptdir & "\testinputfile2.txt" $po_number = FileReadLine($file, 1) $file_count = _FileCountLines($file) For $i = 1 To $file_count     $line = FileReadLine($file, $i)     If StringInStr($po_number, $line) > 0 Then         if _FileWriteToLine($file, $i, "", 1) <> 1 Then ConsoleWrite(@error & @LF) ; added an error check with console output         $count += 1     Else         ExitLoop     EndIf Next MsgBox(0, "Information:", "Count is " & $count & " PO number " & $po_number)

If you run this it will return "Count is 3 PO number is 3022".  The output file is left with two lines of 3022.  This is because you are deleting the line that matches your number with 

_FileWriteToLine($file, $i, "", 1)

 while using an increment variable to read the file line by line.

 

1ST read in loop - file has 5 lines = 3022 

2ND read in loop - file has 4 lines = 3022 and you start testing at line 2 skipping line 1 (which is 3022)

3RD read in loop - file has 3 lines = 3022 skipping line 1 and 2...

 

Not only is this a logical error but it is terribly inefficient (see HELP file doc for FileReadLine).

 

Let's say that we change the _FileWriteLine to

_FileWriteToLine($file, $i, "  ", 1)

to write a blank space rather than delete the line.

 

Now the message is "Count is 5 PO number is 3022" and there are 5 blank lines in the output file (as we expect).  Probably not what you want but logically correct. 

 

Given all of the above it is better to read the file to either a string or an array, process the string/array and write the file back from the string/array.

 

A couple of examples of this have been posted in previous replies.

 

I hope this helps.  Right now your best friend is the HELP file.

 

kylomas

 

edit: spelling


Edited by kylomas, 12 December 2013 - 01:31 AM.

  • esahtar90 likes this

"Really?, How Do you know the're not random numbers?"

 

Forum Rules         Procedure for posting code

 

"A child educated only at school is an uneducated child."

    - George Santayana

 

"Never miss a good chance to shut up."

    - Will Rogers
 


#8 Malkey

Malkey

  • Active Members
  • PipPipPipPipPipPip
  • 1,516 posts

Posted 12 December 2013 - 11:22 AM

.....
The whole code is function, everytime the fucntion gets called it returns the first numbers of the text file and number along with the number of occurance.
.....

I have interpretated the above as you wanting to have this returned.

3022  5 3023  5 3024  5 3025  5 3026  5 3027  5 3028  5 3029  5 3030  5 3031  5

And this example returns the above from the posted testinputfile.txt file.

Local $file = "testinputfile.txt" ; This .txt file is in same directory as this .au3 script. Otherwise, use full path .txt filename. Local $sFileContents = FileRead($file) Local $sOutput = "" Local $sFirstLine, $iNum While $sFileContents <> ""     ; Next 2 command lines assume the newline characters used in the file is @LF only. Sometimes @CRLF is used.     ; Therefore, @CRLF is to replace @LF in the commands in these following 2 lines.     ;$sFirstLine = StringMid($sFileContents, 1, StringInStr($sFileContents, @LF) - 1) ; First line in string.     ;$sFileContents = StringReplace($sFileContents, $sFirstLine & @LF, "") ; Deletes all occurrences of first line in string.     ; --- Use either above 2 lines, Or, use next 2 lines -----     $sFirstLine = StringRegExpReplace($sFileContents, "(?s)^(\V+).*$", "\1")      ; First line in string.     $sFileContents = StringRegExpReplace($sFileContents, $sFirstLine & "\v*", "") ; Deletes all occurrences of first line in string.     $iNum = @extended ; Number of replacements in above StringRegExpReplace command.     $sOutput &= $sFirstLine & "  " & $iNum & @LF WEnd ConsoleWrite($sOutput & @LF) ; Or write $sOutput to a file if needed.

  • esahtar90 likes this




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users