Jump to content
Sign in to follow this  
dss

AutoIt masters - need assistance comparing and deleting

Recommended Posts

dss

I have very minimal knowledge of AutoIt. I come from basic/batch/vbscript/wisescript environment. I am learning AutoIt as I type this. I'm hoping someone can help me out / point me in the right direction. AutoIt has helped me in the past with many tasks. Again, I am a beginner here.

I'm looking for a script that compares two text files (contains listing of files) and sorting out the differences. Once the differences have been sorted out, I want to delete the files that are "different."

For example:

[file1.txt content]

c:dog.txt

c:cat.txt

c:mouse.txt

[file2.txt content]

c:dog.txt

c:cat.txt

c:mouse.txt

c:bear.txt

Logic:

Difference = c:bear.txt

Delete c:bear.txt

Any help would be appreciated.

-DS

Edited by dss

Share this post


Link to post
Share on other sites
Malkey

The following results are from testing the below script:-

Two 24KB text files with approx. 970 lines each, took 0.49 secs.

Comparing a 24KB text file with approx. 1010 lines

with a 30KB text file with approx. 1220 lines took 1.04 secs

Comparing a 24KB text file with approx. 1010 lines

with a 49KB text file with approx. 1940 lines took 3.37 secs

Comparing two 49KB text files with approx. 1940 lines each, did not work correctly on my xp.

"Comparing" meaning, creating an array containing lines that do not appear in both files.

;#cs
If FileExists("file1.txt") = 0 Then FileWrite("file1.txt", _
        "c:\ dog.txt" & @CRLF & _
        "c: \ cat.txt" & @CRLF & _
        "c:\mouse.txt" & @CRLF & _
        "c:\spider.txt")

If FileExists("file2.txt") = 0 Then FileWrite("file2.txt", _
        "c:\ pig.txt" & @CRLF & _
        "c:\ dog.txt" & @CRLF & _
        "c: \ cat.txt" & @CRLF & _
        "c:\horse.txt" & @CRLF & @CRLF & _
        "c:\mouse.txt" & @CRLF & _
        "c:\bear.txt")
;#ce

Local $begin = TimerInit()
Local $aDeleteList = _FileDiffences("file1.txt", "file2.txt", 0) ;
ConsoleWrite("Time taken: " & Round(TimerDiff($begin) / 1000, 4) & " secs" & @LF) ;

If IsArray($aDeleteList) Then
    ConsoleWrite("Deleting Files:" & @LF)
    For $i = 0 To UBound($aDeleteList) - 1
        ConsoleWrite($aDeleteList[$i] & @LF)
        If FileExists($aDeleteList[$i]) Then FileDelete($aDeleteList[$i])
    Next
EndIf

FileDelete("file1.txt")
FileDelete("file2.txt")


; Description: Compares two files by lines and returns the lines that do not exist in both files.
; Returns:- Array of the lines that do not exist in both files; or,
;          Zero when both files are the same.
Func _FileDiffences($file1, $file2, $iCaseSensitive = 0)
    Local $sCS = ""
    If ($iCaseSensitive = 0) Then $sCS = "(?i)"
    Local $sFile1Contents = StringRegExpReplace(FileRead($file1), "(\R+)", @CRLF) ; Remove blank lines
    Local $sFile2Contents = StringRegExpReplace(FileRead($file2), "(\R+)", @CRLF) ; Remove blank lines
    ;ConsoleWrite($sFile2Contents & @LF)
    If (($iCaseSensitive <> 0) And ($sFile1Contents = $sFile2Contents)) Or (($iCaseSensitive = 0) And ($sFile1Contents == $sFile2Contents)) Then Return 0

    ; Create part of Reg Exp pattern
    Local $sFile1REs = "(?:" & StringRegExpReplace(StringRegExpReplace(StringStripWS($sFile1Contents, 2), '([\^\\\[\]\-\|\.\(\)\?\*\+\{\}\$''])', "\\$1"), "(\v+)", ")|(?:") & ")"
    Local $sFile2REs = "(?:" & StringRegExpReplace(StringRegExpReplace(StringStripWS($sFile2Contents, 2), '([\^\\\[\]\-\|\.\(\)\?\*\+\{\}\$''])', "\\$1"), "(\v+)", ")|(?:") & ")"
    ;ConsoleWrite($sFile1REs & @LF)
    ;ConsoleWrite($sFile2REs & @LF)

    Local $sNonMatchingLines = StringStripWS(StringRegExpReplace($sFile2Contents & @CRLF, $sCS & "((" & $sFile1REs & ")(?:\R+))", ""), 7) & @CRLF & _
            StringRegExpReplace($sFile1Contents & @CRLF, $sCS & "((" & $sFile2REs & ")(?:\R+))", "")
    ;ConsoleWrite($sNonMatchingLines & @LF)

    Return StringRegExp($sNonMatchingLines, "([^\v]+)", 3)
EndFunc   ;==>_FileDiffences

Share this post


Link to post
Share on other sites
AZJIO

$Path_In1 = @ScriptDir & 'test_in1.txt'
$Path_In2 = @ScriptDir & 'test_in2.txt'
$Path_Out = @ScriptDir & 'test_Out.txt'
$sText1 = FileRead($Path_In1)
$sText2 = FileRead($Path_In2)

$sText_Out = _Alike_Lines($sText1, $sText2)
If @error Then
    MsgBox(0, 'Error', 'Error = ' & @error)
    Exit
Else
    $hFile = FileOpen($Path_Out, 2) ; пишем в файл
    FileWrite($hFile, $sText_Out)
    FileClose($hFile)
EndIf

; @error = 2 - Not found
; @error = 2 - Не найдено
; не учитывает регистр String = StRiNg = STRING
; not case sensitive, String = StRiNg = STRING
Func _Alike_Lines($sText1, $sText2, $sep = @CRLF)
    Local $i, $k, $aText, $s, $Trg = 0, $LenSep

    If StringInStr($sText1 & $sText2, '[') And $sep <> '[' Then ; если сбойный символ есть до заменяем его
        For $i = 0 To 255
            $s = Chr($i)
            If Not StringInStr($sText1 & $sText2, $s) Then
                If StringInStr($sep, $s) Then ContinueLoop
                $sText1 = StringReplace($sText1, '[', $s)
                $sText2 = StringReplace($sText2, '[', $s)
                $Trg = 1
                ExitLoop
            EndIf
        Next
        If Not $Trg Then Return SetError(1, 0, '')
    EndIf

    $LenSep = StringLen($sep)

    $aText = StringSplit($sText1, $sep, 1) ; Создаём переменные первого файла
    For $i = 1 To $aText[0]
        Assign($aText[$i] & '/', -2, 1)
    Next
    Assign('/', 2, 1)

    $aText = StringSplit($sText2, $sep, 1)

    $k = 0
    $sText1 = ''
    For $i = 1 To $aText[0]
        Assign($aText[$i] & '/', Eval($aText[$i] & '/') + 1, 1) ; создаём локальные переменные или увеличиваем значение для уже созданных
        If Eval($aText[$i] & '/') = -1 Then
            $sText1 &= $aText[$i] & $sep
            $k += 1
        EndIf
    Next
    If $k = 0 Then Return SetError(2, 0, '')
    If $Trg Then $sText1 = StringReplace($sText1, $s, '[')
    Return StringTrimRight($sText1, $LenSep)
EndFunc

If I did not understand, here's another option

$Path_In1 = @ScriptDir & 'test_in1.txt'
$Path_In2 = @ScriptDir & 'test_in2.txt'
$Path_Out = @ScriptDir & 'test_Out.txt'
$sText1 = FileRead($Path_In1)
$sText2 = FileRead($Path_In2)

$sText_Out = _Unique_Lines_Text2($sText1, $sText2)
If @error Then
    MsgBox(0, 'Error', 'Error = ' & @error)
    Exit
Else
    $hFile = FileOpen($Path_Out, 2) ; пишем в файл
    FileWrite($hFile, $sText_Out)
    FileClose($hFile)
EndIf

; @error = 2 - Not found
; @error = 2 - Не найдено
; не учитывает регистр String = StRiNg = STRING
; not case sensitive, String = StRiNg = STRING
Func _Unique_Lines_Text2($sText1, $sText2, $sep = @CRLF)
    Local $i, $k, $aText, $s, $Trg = 0, $LenSep

    If StringInStr($sText1 & $sText2, '[') And $sep <> '[' Then ; если сбойный символ есть до заменяем его
        For $i = 0 To 255
            $s = Chr($i)
            If Not StringInStr($sText1 & $sText2, $s) Then
                If StringInStr($sep, $s) Then ContinueLoop
                $sText1 = StringReplace($sText1, '[', $s)
                $sText2 = StringReplace($sText2, '[', $s)
                $Trg = 1
                ExitLoop
            EndIf
        Next
        If Not $Trg Then Return SetError(1, 0, '')
    EndIf

    $LenSep = StringLen($sep)

    $aText = StringSplit($sText1, $sep, 1) ; Создаём переменные первого файла
    For $i = 1 To $aText[0]
        Assign($aText[$i] & '/', 2, 1)
    Next
    Assign('/', 2, 1)

    $aText = StringSplit($sText2, $sep, 1)

    $k = 0
    $sText1 = ''
    For $i = 1 To $aText[0]
        Assign($aText[$i] & '/', Eval($aText[$i] & '/')+1, 1) ; создаём локальные переменные или увеличиваем значение для уже созданных
        If Eval($aText[$i] & '/') = 1 Then
            $sText1 &= $aText[$i] & $sep
            $k += 1
        EndIf
    Next
    If $k = 0 Then Return SetError(2, 0, '')
    If $Trg Then $sText1 = StringReplace($sText1, $s, '[')
    Return StringTrimRight($sText1, $LenSep)
EndFunc
Edited by AZJIO

Share this post


Link to post
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
Sign in to follow this  

  • Similar Content

    • reida
      By reida
      Hello. On page there is mail address. How to keep in a text file this address? 
      It is page and email
      https://alpari.com/
      info@alpari.com
    • nooneclose
      By nooneclose
      My program has to first search for names in Column D that do not match up with column C. I got that search to work using arrays. It was slow and I could not figure out how to delete them so I just manually put coded the names that do not belong. I found their cell location but I do not know how to store that location and delete it.
      This is what I have so far.
      Local $NameToDelete1[6]  = _Excel_RangeFind($OpenWorkbook, "Smith, Bill") _ArrayDisplay($NameToDelete1, "Excel UDF: _Excel_RangeFind Example 1", "", 0, "|", "Sheet|Name|Cell|Value|Formula|Comment") _Excel_RangeDelete($OpenWorkbook.ActiveSheet, $NameToDelete1[2], $xlShiftUp)  
      Please help, I wanted to have this program done yesterday but I did not see this problem until yesterday. 
    • caramen
      By caramen
      Hey.  
       
      I requested help about how to get a value from a text in a variable. 
      Now i know how to do that. But i learned with the command FileRead. Now i whould like to know how to replace the command :
      FileRead('Dossier.txt') The purpose is to read a webpage text. To find some value inside. 
       
      Btw i tryed to play with WindowsInfo.au3 but i dont got much thing.  
    • Bllee
      By Bllee
      every time i press "delete button" delete a line, but i can't add new line with info. the id line write normally but i can't change or add new info
      obs: looking at the "includes" one realizes that already tried of everything that knew
      my code
      #include <ButtonConstants.au3> #include <EditConstants.au3> #include <GUIConstantsEx.au3> #include <GUIListBox.au3> #include <StaticConstants.au3> #include <WindowsConstants.au3> #include <GUIConstantsEx.au3> #include <GuiImageList.au3> #include <GuiListView.au3> #include <GUIConstantsEx.au3> #include <GuiListView.au3> #include <MsgBoxConstants.au3> #include <WinAPI.au3> #include <StringConstants.au3> #include <Array.au3> #include <GuiListBox.au3> #Region ### START Koda GUI section ### Form= $Form1 = GUICreate("Form1", 612, 480, 192, 154) $MenuItem1 = GUICtrlCreateMenu("&Arquivo") $MenuItem2 = GUICtrlCreateMenuItem("Salvar Ctrl+S", $MenuItem1, $SS_CENTER) $MenuItem4 = GUICtrlCreateMenuItem("Carregar Ctrl+O", $MenuItem1, $SS_CENTER) $MenuItem3 = GUICtrlCreateMenuItem("Salvar Como Shitft+Ctrl+S", $MenuItem1, $SS_CENTER) $Group1 = GUICtrlCreateGroup("", 21, 8, 569, 97, $SS_CENTER) $Input1 = GUICtrlCreateInput("ID COR", 122, 32, 97, 21, $SS_CENTER) $Input2 = GUICtrlCreateInput("REGIÃO", 138, 64, 249, 21, $SS_CENTER) $Input3 = GUICtrlCreateInput("Label", 264, 30, 121, 21, $SS_CENTER) $Label1 = GUICtrlCreateLabel("Label", 232, 32, 30, 17, $SS_CENTER) $Button1 = GUICtrlCreateButton("Capturar Cor", 42, 30, 75, 25, $SS_CENTER) $Button2 = GUICtrlCreateButton("Capturar Região", 42, 62, 91, 25, $SS_CENTER) $Button3 = GUICtrlCreateButton("ADD", 442, 24, 113, 33) $Button5 = GUICtrlCreateButton("Delet", 442, 64, 113, 33) $Group2 = GUICtrlCreateGroup("Editar ID selecionado", 8, 384, 601, 57, $SS_CENTER) $Input7 = GUICtrlCreateInput("ID", 10, 402, 40,21, $SS_CENTER) $Input4 = GUICtrlCreateInput("COR", 51, 402, 121, 21, $SS_CENTER) $Input5 = GUICtrlCreateInput("REGIÃO", 173, 402, 249, 21, $SS_CENTER) $Input6 = GUICtrlCreateInput("LABEL", 423, 402, 121, 21, $SS_CENTER) $Button4 = GUICtrlCreateButton("\/", 544, 400, 30, 25, $SS_CENTER) $Button6 = GUICtrlCreateButton("/\", 574, 400, 30, 25, $SS_CENTER) ; Add column Global $id = Int(0) $List1 = GUICtrlCreateListView("",5, 120, 601, 253, $SS_CENTER) _GUICtrlListView_AddColumn($List1, "ID",40) _GUICtrlListView_AddColumn($List1, "COR",100) _GUICtrlListView_AddColumn($List1, "COORDENADA",305) _GUICtrlListView_AddColumn($List1, "LABEL",150) GUISetState(@SW_SHOW) #EndRegion ### END Koda GUI section ### While 1 $nMsg = GUIGetMsg() Switch $nMsg Case $GUI_EVENT_CLOSE Exit Case $MenuItem2 MsgBox($MB_SYSTEMMODAL, "ctrl + s", "Nothing Here",1) Case $MenuItem3 MsgBox($MB_SYSTEMMODAL, "shift+ctrl s", "Nothing Here",1) Case $MenuItem4 MsgBox($MB_SYSTEMMODAL, "ctrl + o", "Nothing Here",1) Case $Button1 MsgBox($MB_SYSTEMMODAL, "Capturar cor", "Aperte espaço para capturar a cor") GUICtrlSetData($Input1,MouseColor()) Case $Button2 MsgBox($MB_SYSTEMMODAL, "capturar região", "Aperte espaço para capturar a posição inicial") local $mouse = MouseGetPos() $x_init = $mouse[0] $y_init = $mouse[1] MsgBox($MB_SYSTEMMODAL, "capturar região", "Aperte espaço para capturar a posição final") local $mouse = MouseGetPos() $x_end = $mouse[0] $y_end = $mouse[1] GUICtrlSetData($Input2,$x_init&','&$y_init&' ; '&$x_end&','&$y_end) Case $Button3 _GUICtrlListView_AddItem($List1, $id, 1) ; id _GUICtrlListView_AddSubItem($List1, $id, GUICtrlRead($Input1), 1, 1) ;cor _GUICtrlListView_AddSubItem($List1, $id, GUICtrlRead($Input2), 2, 1) ;coordenada _GUICtrlListView_AddSubItem($List1, $id, GUICtrlRead($Input3), 3, 1) ;label $id= $id + 1 Case $Button4 $Item = _GUICtrlListView_GetSelectedIndices($List1) $Sid = _GUICtrlListView_GetItem($List1, Number($Item),0) $Scor = _GUICtrlListView_GetItem($List1, Number($Item),1) $Scord = _GUICtrlListView_GetItem($List1, Number($Item),2) $Slabel = _GUICtrlListView_GetItem($List1, Number($Item),3) ; get info GUICtrlSetData($Input7,$Sid[3]) GUICtrlSetData($Input4,$Scor[3]) GUICtrlSetData($Input5,$Scord[3]) GUICtrlSetData($Input6,$Slabel[3]) Case $Button5 _GUICtrlListView_DeleteItemsSelected($List1) Case $Button6 ; give back inf if GUICtrlRead($Input7) <> "ID" Then _GUICtrlListView_SetItem($List1, GUICtrlRead($Input4), GUICtrlRead($Input7),1) ;cor _GUICtrlListView_SetItem($List1, GUICtrlRead($Input5), GUICtrlRead($Input7),2) ;coordenada _GUICtrlListView_SetItem($List1, GUICtrlRead($Input6), GUICtrlRead($Input7),3) ;coordenada EndIf EndSwitch WEnd Func MouseColor() local $mouse = MouseGetPos() Return Hex(PixelGetColor($mouse[0],$mouse[1]), 6) EndFunc  
    • therks
      By therks
      I'm trying to create a simple clock widget that automatically scales the text to the size of the window. I came up with the following method, but it doesn't work as well as I'd like. It especially has trouble scaling to the width of the window for some reason (in the example, try resizing the window to be narrow and tall).
      Does anyone have a better method?
      #include <Misc.au3> #include <WinAPIConv.au3> #include <GUIConstants.au3> #include <GDIPlus.au3> Opt('MustDeclareVars', 1) Global $_FONT_FAMILY = 'Arial', $_LB_TEXT Main() Func Main() _GDIPlus_Startup() Local $hGUI GUIRegisterMsg($WM_SIZE, WM_SIZE) $hGUI = GUICreate('', 300, 100, Default, Default, $WS_OVERLAPPEDWINDOW, BitOR($WS_EX_TOOLWINDOW, $WS_EX_TOPMOST)) $_LB_TEXT = GUICtrlCreateLabel('This is a string', 0, 0, 300, 100, BitOR($SS_CENTER, $SS_CENTERIMAGE)) GUICtrlSetFont($_LB_TEXT, _MeasureString($hGUI, GUICtrlRead($_LB_TEXT), $_FONT_FAMILY), 0, 0, $_FONT_FAMILY, 5) GUISetState() Local $iGM While 1 $iGM = GUIGetMsg() Switch $iGM Case $GUI_EVENT_CLOSE ExitLoop EndSwitch WEnd _GDIPlus_Shutdown() EndFunc Func WM_SIZE($hWnd, $iMsg, $wParam, $lParam) GUICtrlSetFont($_LB_TEXT, _MeasureString($hWnd, GUICtrlRead($_LB_TEXT), $_FONT_FAMILY), 0, 0, $_FONT_FAMILY, 5) EndFunc Func _MeasureString($hWnd, $sString, $sFont = 'Arial') Local $iError, $aSize, $hGraphic, $hFormat, $hFamily, $tLayout, $iFontSize, $hFont, $aInfo If Not IsHWnd($hWnd) Then $hWnd = GUICtrlGetHandle($hWnd) EndIf $aSize = WinGetClientSize($hWnd) $hGraphic = _GDIPlus_GraphicsCreateFromHWND($hWnd) $hFormat = _GDIPlus_StringFormatCreate() $hFamily = _GDIPlus_FontFamilyCreate($sFont) $tLayout = _GDIPlus_RectFCreate(0, 0, $aSize[0], $aSize[1]) $iFontSize = 0 Do If Not $hFamily Then $iError = 1 $iFontSize = 10 ExitLoop EndIf $iFontSize += 1 $hFont = _GDIPlus_FontCreate($hFamily, $iFontSize, 0) $aInfo = _GDIPlus_GraphicsMeasureString($hGraphic, $sString, $hFont, $tLayout, $hFormat) _GDIPlus_FontDispose($hFont) If $aInfo[1] = 0 Then ExitLoop Until DllStructGetData($aInfo[0], 3) >= $aSize[0] Or DllStructGetData($aInfo[0], 4) >= $aSize[1] $iFontSize -= 1 _GDIPlus_FontFamilyDispose($hFamily) _GDIPlus_StringFormatDispose($hFormat) _GDIPlus_GraphicsDispose($hGraphic) Return SetError($iError, 0, $iFontSize) EndFunc
×