Jump to content

Delete lines from text file by string match


SmartiePants
 Share

Recommended Posts

I wanted to find a code on here, but everyone was posting their non-working scripts and I couldn't find a good working one, so I made a simple script on my own.

; DeleteLine.au3 by SmartiePants
; Will read input in Read Only mode, so it will not be altered.
; will output 2 files based on input file by appending new name to the old file name
; will overwrite output files if script is run more than once on the same input file
$prompt = FileOpenDialog("Open text file", @WorkingDir, "All (*.*)", 3)
If @error = 1 Then Exit; cancelled
; Static filename for output files
$outputGood = $prompt & ".good_lines.txt" ; Lines that did not have the string within them
$outputBad = $prompt & ".bad_lines.txt"

$handleInputFile = FileOpen($prompt, 0) ; open the file in read-only mode
If $handleInputFile = -1 Then
    MsgBox(16, "Error", "Unable to open input text file.")
    Exit
EndIf

$string = InputBox("", "Lines with this string will be deleted", "-thumb-")
If $string = "" Then
    MsgBox(16, "Error", "String can't be empty.")
    Exit
EndIf

$handleGoodOutput = FileOpen($outputGood, 2) ; overwrite destination file if exists
If $handleGoodOutput = -1 Then
    MsgBox(16, "Error", "Unable to create output text file.")
    Exit
EndIf
$handleBadOutput = FileOpen($outputBad, 2) ; overwrite destination file if exists
If $handleBadOutput = -1 Then
    MsgBox(16, "Error", "Unable to create output text file.")
    Exit
EndIf
$time = TimerInit()
While 1
    $line = FileReadLine($handleInputFile) ; read next line
    If @error = -1 Then ExitLoop ; exit at EOF
    If Not StringInStr($line, $string) Then
        FileWriteLine($handleGoodOutput, $line) ; write good lines
    Else
        FileWriteLine($handleBadOutput, $line) ; write bad lines
    EndIf
WEnd
FileClose($handleInputFile)
FileClose($handleGoodOutput)
FileClose($handleBadOutput)
MsgBox(64, "Done", "in " & Round(TimerDiff($time), 0) & "ms")

[font="Comic Sans MS"]It's my first day.[/font]View and move images to subdirectories by pressing a key in XnView

Link to comment
Share on other sites

An other way ! Posted Image

#Include <Array.au3>
#Include <File.au3>

Global $_Array
_FileReadToArray ( 'c:\file.txt', $_Array )
$_Array = _DeleteArrayElementWithStringInstr ( $_Array, '-thumb-' )
_FileWriteFromArray ( 'c:\file.txt', $_Array, 1 )
Exit

Func _DeleteArrayElementWithStringInstr ( $_Array, $_String )
    Local $_Item
    For $_Element In $_Array
        If StringInStr ( $_Element, $_String ) <> 0 Then
            _ArrayDelete ( $_Array, $_Item )
        Else
            $_Item+=1
        EndIf
    Next
    Return ( $_Array )
EndFunc ;==> _DeleteArrayElementWithStringInstr ( )

AutoIt 3.3.14.2 X86 - SciTE 3.6.0WIN 8.1 X64 - Other Example Scripts

Link to comment
Share on other sites

An other way ! Posted Image

I like array approach too, and I use it for almost everything I create, but I wanted to make a script quicker and thought my 453 millisecond processing of a 3500 line text file was pretty good. :>

I am suprised with the For $_Element In $_Array line, which ends up requring the $_Item counter. I am used to For $i = 1 to $_Array[0]. This is an interesting approach with fewer lines of code than my average array script. Thanks :unsure:

[font="Comic Sans MS"]It's my first day.[/font]View and move images to subdirectories by pressing a key in XnView

Link to comment
Share on other sites

  • 5 years later...
Quote
#Include <Array.au3>
#Include <File.au3>

Global $_Array
_FileReadToArray ( 'c:\file.txt', $_Array )
$_Array = _DeleteArrayElementWithStringInstr ( $_Array, '-thumb-' )
_FileWriteFromArray ( 'c:\file.txt', $_Array, 1 )
Exit

Func _DeleteArrayElementWithStringInstr ( $_Array, $_String )
    Local $_Item
    For $_Element In $_Array
        If StringInStr ( $_Element, $_String ) <> 0 Then
            _ArrayDelete ( $_Array, $_Item )
        Else
            $_Item+=1
        EndIf
    Next
    Return ( $_Array )
EndFunc ;==> _DeleteArrayElementWithStringInstr ( )

Error is showing in this code

 

err.png

Link to comment
Share on other sites

  • Moderators

@Student_coder, you have to put the file extension (.txt) in order for AutoIt to read from the file. If your text file is named 'new_test_cases', you need to have 'new_test_cases.txt' in both your _FileReadToArray and _FileWriteFromArray calls. Also, if the text file is not in the same directory as your script, you need to specify the full path.

"Profanity is the last vestige of the feeble mind. For the man who cannot express himself forcibly through intellect must do so through shock and awe" - Spencer W. Kimball

How to get your question answered on this forum!

Link to comment
Share on other sites

  • 2 years later...

Hi all, I have been testing the above code (which works great), but was wondering if there was a way to only delete one instance from the array as opposed to all of them. Say for instance the word "White" exists in the array several times, I would only like to delete the first 'White' from the array, and then when I run the script again, it will find and delete the second 'White' instance. Is there a particular function that I could read up about that may be able to do this? I have tried playing around and tweaking the above code to no avail.  Thank you

Link to comment
Share on other sites

As soon as you find the first one and delete it, "exitloop" and exit.

 

Spoiler

Renamer - Rename files and folders, remove portions of text from the filename etc.

GPO Tool - Export/Import Group policy settings.

MirrorDir - Synchronize/Backup/Mirror Folders

BeatsPlayer - Music player.

Params Tool - Right click an exe to see it's parameters or execute them.

String Trigger - Triggers pasting text or applications or internet links on specific strings.

Inconspicuous - Hide files in plain sight, not fully encrypted.

Regedit Control - Registry browsing history, quickly jump into any saved key.

Time4Shutdown - Write the time for shutdown in minutes.

Power Profiles Tool - Set a profile as active, delete, duplicate, export and import.

Finished Task Shutdown - Shuts down pc when specified window/Wndl/process closes.

NetworkSpeedShutdown - Shuts down pc if download speed goes under "X" Kb/s.

IUIAutomation - Topic with framework and examples

Au3Record.exe

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...