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

    • Sally1801
      By Sally1801
      Hello,
      i need help in deleting files from a server. The function "_FTP_DirDelete" only deletes a directory when its empty. I need to delete a non empty directory. I also can not delete the files in this directory first, because the files are PAG and DIR files in a .DAV directory and FTPEx.au3 doesnt like a directory starting with a ".".
      Any ideas?
      Thx, Sally
    • dadalt95
      By dadalt95
      Hi!
      I want to get the signal in this website:
      https://binary-signal.com/pt/chart/eurusd
      I have tried using _IEBodyReadText  and some _StringBetween. What happens is that the text are being update every tick and _IEBodyReadText doesn't.
      To perform the update I used  _IEAction($oIE, "refresh") but it's not good because the website block me after some time due too many requests..
      Is there any other way to get this text every tick?
      PS: The text I want to get is WAIT, CALL or PUT.
       
      Here is the code:
      global $oIE = _IECreate ('https://binary-signal.com/pt/chart/eurusd', 0, 1 , 1 , 0) Local $sText = _IEBodyReadText($oIE) $result = _StringBetween ( $sText , 'PUTEUR/USD on Binary-signal.com', 'sinal está PRONTA') ;MsgBox ( 0, "asf", $result[0]) $espera=StringInStr($result[0], "WAIT") $compra=StringInStr($result[0], "CALL") $venda=StringInStr($result[0], "PUT") ;MsgBox($MB_SYSTEMMODAL, "", $espera) $n=0 $c=0 Captar() Func Captar() ;_IENavigate($oIE, "https://binary-signal.com/pt/chart/eurusd") ;MsgBox($MB_SYSTEMMODAL, "", $n) Local $sText = _IEBodyReadText($oIE) $result = _StringBetween ( $sText , 'PUTEUR/USD on Binary-signal.com', 'sinal está PRONTA') If (Not $compra=0) And $n=0 Then MsgBox($MB_SYSTEMMODAL, "", "COMPRE") $n=1 $c=$c+1 ;_IEAction($oIE, "refresh") Sleep(60000) Captar() ElseIf (Not $venda=0) And $n=0 Then MsgBox($MB_SYSTEMMODAL, "", "VENDA") $c=$c+1 $n=1 ;_IEAction($oIE, "refresh") ;MsgBox($MB_SYSTEMMODAL, "", $n) Sleep(60000) Captar() ElseIf (Not $venda=0) And $n=1 Then ;MsgBox($MB_SYSTEMMODAL, "", "Esperando próxima rodada") $n=1 ;MsgBox($MB_SYSTEMMODAL, "", $n) ;_IEAction($oIE, "refresh") Sleep(60000) Captar() ElseIf (Not $venda=0) And $n=1 Then ;MsgBox($MB_SYSTEMMODAL, "", "Esperando próxima rodada") $n=1 ;MsgBox($MB_SYSTEMMODAL, "", $n) ;_IEAction($oIE, "refresh") Sleep(60000) Captar() Else ;MsgBox("", "", "ESPERE") $n=0 Sleep(1000) ;_IEAction($oIE, "refresh") Local $sText = _IEBodyReadText($oIE) $result = _StringBetween ( $sText , 'PUTEUR/USD on Binary-signal.com', 'sinal está PRONTA') Captar() EndIf EndFunc  
    • vin1
      By vin1
      i need a script that can replace words in text with other words from a words list
      it has to have 2 edit boxes input/output and a button "run"
      from word_list.txt it choses which word to replace with. words are separated with commas for multiple choice
       

       
       

       
       
      ; AutoIt GUI Example ; Created: 17/01/2005 - CyberSlug ; Modifed: 05/12/2011 - guinness ; Modifed: 09/06/2014 - mLipok #Region INCLUDE #include <AVIConstants.au3> #include <GuiConstantsEx.au3> #include <TreeViewConstants.au3> #EndRegion INCLUDE #Region GUI GUICreate("Sample GUI", 400, 420) GUISetIcon(@SystemDir & "\mspaint.exe", 0) #EndRegion GUI #Region EDIT GUICtrlCreateEdit(@CRLF & " Sample Edit Control", 10, 10, 380, 175) GUICtrlSetTip(-1, '#Region EDIT') #EndRegion EDIT #Region EDIT2 GUICtrlCreateEdit(@CRLF & " Sample Edit Control", 10, 185, 380, 175) GUICtrlSetTip(-1, '#Region EDIT') #EndRegion EDIT2 #Region BUTTON GUICtrlCreateButton("Sample Button", 10, 360, 100, 30) GUICtrlSetTip(-1, '#Region BUTTON') #EndRegion BUTTON #Region GUI MESSAGE LOOP GUISetState(@SW_SHOW) While 1 Switch GUIGetMsg() Case $GUI_EVENT_CLOSE ExitLoop EndSwitch WEnd GUIDelete() #EndRegion GUI MESSAGE LOOP  
    • kneze
      By kneze
      hi
      i use from Command Line net user /Domain UserID >> C:\temp\sample.txt to request informations about specific Domain User. Now i wil get Password last set, Password expires, password changeable and all Groups from Global Group Membership of this User to display in a MsgBox. With FUNC _readGroups i can check which position is group date of last password set but i don't know how to get needed informations as i wrote at the beginning.
      Thanks in advance for any hint how can i solve it.
      #cs ---------------------------------------------------------------------------- AutoIt Version: 3.3.14.3 Author: myName Script Function: Template AutoIt script. #ce ---------------------------------------------------------------------------- ; Script Start - Add your code below here #include <File.au3> $FilePath=@ScriptDir &"\sample.txt" $StringToSearch="Password last set" $CaseSense=0 $Lines=_FileCountLines($FilePath) $hFile=FileOpen($FilePath,0) $LinesCount=_FileCountLines($FilePath) For $i=0 To Number($Lines) $Test=FileReadLine($hFile,$i) If StringInStr($Test,$StringToSearch,$CaseSense) Then $foundLine = $i _readGroups($foundLine,$LinesCount,$i) ;MsgBox(0,"","The string " & $StringToSearch & " was found on line " & $i) ;MsgBox(0,"","Lines found: " & $LinesCount) ExitLoop EndIf Next FileClose($hFile) FUNC _readGroups($foundLine,$LinesCount,$i) ;For $j=$foundLine To Number($LinesCount) $lLine=FileReadLine($hFile,$i) ;$split = StringSplit($lLine," ") $split = StringSplit(StringStripWS($lLine,1)," ") For $x = 1 To $split[0] MsgBox(0,$x,$split[$x]) Next ;MsgBox(0,"",$split[15]& " " & $split[16]) ;Next EndFunc  
      sample.txt
    • Ambient
      By Ambient
      I have tried several way sto get this to work to no avail. Any help would be appreciated. #include <ListViewConstants.au3> #include <GuiListView.au3> #include "GuiListViewEx.au3" $idItem = GUICtrlCreateListViewItem($r & " | " & $c & $adoRs.Fields("TransactionAmount").value & " | " & $Timestamp & " | " & _StringProper($adoRs.Fields("Tillid").value) & @CRLF & @CRLF & "Card Number : " & $cardnum & " " , $idListView) ConsoleWrite( "IDITEM" & $idItem) If STRINGLEFT($adoRs.Fields("TransactionAmount").value,1)= "-" Then Consolewrite(" String is Negative" & @CRLF) ;Drops in Here as expected ;GUICtrlSetColor(-1, $COLOR_RED) ; Colour line if item is negative this didn' work $TxC= _GUICtrlListView_SetTextColor($hListView, $CLR_RED) ; I also tried $TxC= _GUICtrlListView_SetTextColor(-1, 0xFF0000) CONSOLEWRITE("TEXTCOLOUR RETURNED " & $TxC & @crlf) ; This is returning True ELSE Consolewrite(" String is NOT Negative" & @CRLF) EndIf  
×