Jump to content

Find and replace and generate logs


Recommended Posts

2 hours ago, pranaynanda said:

Hi Guys!

I need assistance with this. I can't understand how this works:

#include <File.au3>
#include <Array.au3>
Local $b=0
Local $a=_FileListToArrayRec("E:\Documents\AutoIt\fnr","*",$FLTAR_FILES,$FLTAR_RECUR)
;_ArrayDisplay($a)
For $i=1 To UBound($a)-1 Step 1
;Local $b=0
_FileReadToArray($a[$i],$b)
ConsoleWrite($b)
ConsoleWrite($a)
Next

 

It doesn't work...

this does: but has little to nothing to do with the above, maybe somebody else can find sense in it...

#include <File.au3>
#include <Array.au3>
;~ Local $b
Local $a = _FileListToArrayRec("C:\Windows\Help\", "*") ; use a folder path that you know has a couple of folders in it
_ArrayDisplay($a) ; Display the arrary you just built , this only for checking purposes

; use a FOR loop to go through the array and do stuff to it
For $i = 1 To UBound($a) - 1 Step 1 ;read up on Ubound | used to see how big your array is
;~ _FileReadToArray($a[$i], $b)
    ConsoleWrite($a[$i] & @CRLF) ;See console for the same list that your array display showed
    ;insert function here that performs some task to folder/file one at a time from your array
Next

 

Link to comment
Share on other sites

  • 1 month later...

Guys, I got it working. I will share it once I am able to crack through this problem. I can log changes with what was found and in which file. I cannot however log the line number.
 I am trying to do this:

 

Func _fnr()
$find=InputBox("Find","Find")
$replace=InputBox("Replace With", "Replace With")
$time=_Now()
MsgBox(0,"hello",$time)
Local $logfile= $open & "\" & $time & ".log"
MsgBox(0,"hello",$FileList[0])
    For $i=1 To $FileList[0]
        ;MsgBox(0,"hello",$FileList[$i])
    $a=_ReplaceStringInFile($FileList[$i],$find,$replace)
    FileWriteLine($logfile, $find & " was replaced with " & $replace & " in file " & $FileList[$i])
    Next
MsgBox(0,"Test",$a)
EndFunc

I don't understand how to get across the line number thing.

Link to comment
Share on other sites

I must say i'm not totally understanding what the problem is. But here is a bit code (90% straigtht from the help files) to search and replace text in a file and display a change log.

#include <FileConstants.au3>
#include <MsgBoxConstants.au3>

Local $findString = "Hello World"                   ; find this string
Local $replaceString = "Hello Earth"                ; If found replace with this
Local $sCheckMeFile = "C:\Temp\File1.log"           ; file to read see / _FileListToArray () for reading more then one file at once.
Local $sChangeLogFile = "C:\Temp\Changelog.txt"     ; New file with the changes

; Open the file for reading and store the handle to a variable.
Local $hFileOpen = FileOpen ( $sCheckMeFile, $FO_READ )
If $hFileOpen = -1 Then
    MsgBox ( $MB_SYSTEMMODAL, "", "An error occurred when reading the file." )
    Exit 1
EndIf

; Read File
Local $sFileRead = FileRead ( $hFileOpen )

; Replace Text
Local $sString = StringReplace ( $sFileRead, $findString, $replaceString )

Local $iReplacements = @extended
MsgBox ( $MB_SYSTEMMODAL, "", $iReplacements & " replacements were made AND the NEW string is:" & @CRLF & @CRLF & $sString )

; Write the new string to a changelog.txt file.
FileWrite ( $sChangeLogFile, $sString )

; Close file Handle.
FileClose ( $hFileOpen )

 

Link to comment
Share on other sites

Try this:

Func _fnr()
    $find = InputBox("Find", "Find")
    $replace = InputBox("Replace With", "Replace With")
    $time = _Now()
    MsgBox(0, "hello", $time)
    Local $logfile = $open & "\" & $time & ".log"
    ;MsgBox(0, "hello", $FileList[0])
    For $i = 1 To $FileList[0]
        ;MsgBox(0,"hello",$FileList[$i])
        _ReplaceInFile($sLog, $FileList[$i], $find, $replace)
    Next
    ;MsgBox(0, "Test", $a)
EndFunc   ;==>_fnr

Func _ReplaceInFile($sLog, $sFile, $sSearch, $sReplace)
    Local $hFile = FileOpen($sFile)
    Local $aLines = FileReadToArray($sFile)
    FileClose($hFile)
    For $i = 0 To UBound($aLines) - 1
        If StringReplace($aLines[$i], $sSearch, $sReplace) Then _
                _FileWriteLog($sLog, $sFile & @TAB & $i & ': ' & $sSearch & ' ==> ' & $sReplace & @CRLF)
    Next
    _FileWriteFromArray($sFile, $aLines)
EndFunc   ;==>_ReplaceInFile

and insert needed: #include <File.au3>

Link to comment
Share on other sites

@AutoBert although this does give a lot of hint with what has to be done but it still does not work. It does not even replace the strings.

Edit: I made some changes and the logging works right. I'll implement the find and replace functionality soon. Thanks! I couldn't have done it without you.

Edited by pranaynanda
Link to comment
Share on other sites

Err... A little bug there... the count is serial and inputs all the lines in the file whether or not they have the string in it. So for example if line 15 does not have the string "hello", it still prints that in the log file. How can I make sure only those entries are made when a string is replaced?

Edited by pranaynanda
Link to comment
Share on other sites

sorry i missused the func StringReplace. Here my corrected func:

Func _ReplaceInFile($sLog, $sFile, $sSearch, $sReplace)
    Local $hFile = FileOpen($sFile)
    Local $aLines = FileReadToArray($sFile)
    FileClose($hFile)
    For $i = 0 To UBound($aLines) - 1
        $aLines[$i]=StringReplace($aLines[$i], $sSearch, $sReplace)
        If @extended Then _FileWriteLog($sLog, $sFile & @TAB & $i+1 & ': ' & $sSearch & ' ==> ' & $sReplace & @CRLF)
    Next
    _FileWriteFromArray($sFile, $aLines)
EndFunc   ;==>_ReplaceInFile

the entry in the log:

2016-09-17 20:04:03:654 : temp.txt  1: Motor ==> PowerUnit

if changing _FileWriteLog to FileWrite it would look:

temp.txt    1: Motor ==> PowerUnit

 

Edited by AutoBert
Link to comment
Share on other sites

Another piece of help needed guys. I was using this UDF which works flawlessly. I basically wanted to create a dictionary of words that could find and replace and generate logs in one go. Ideal for deployments that require cloning in my experience.

This is my code right now. I know a lot is commented but basically for testing but most of it works. I also know that the code looks very messy at this instance but I promise to clean it once I am done with implementing everything that I need. Anything else will be a minor top-up improvement.

#include <GuiConstantsEx.au3>
#include <File.au3>
#include <Array.au3>
#include <Date.au3>
#include <ListViewEditInput.au3>
#include <GuiListView.au3>

;#cs


#include <ButtonConstants.au3>
#include <EditConstants.au3>
#include <GUIConstantsEx.au3>
#include <GUIListBox.au3>
#include <ListViewConstants.au3>
#include <WindowsConstants.au3>
#Region ### START Koda GUI section ### Form=
$Form1 = GUICreate("Find and Replace", 621, 627, 192, 124)
$Input1 = GUICtrlCreateInput("Source Folder", 120, 32, 417, 21)
$List1 = GUICtrlCreateList("", 120, 64, 417, 214)
GUICtrlSetResizing(-1, $GUI_DOCKAUTO)
$Button1 = GUICtrlCreateButton("Browse", 48, 32, 65, 25)
$ListView1 = GUICtrlCreateListView("Find|Replace With", 120, 304, 417, 241)
GUICtrlSendMsg(-1, $LVM_SETCOLUMNWIDTH, 0, 205)
GUICtrlSendMsg(-1, $LVM_SETCOLUMNWIDTH, 1, 208)
GUICtrlCreateListViewItem('|',$ListView1)
$Button2 = GUICtrlCreateButton("Replace", 128, 568, 409, 41)
$Button3 = GUICtrlCreateButton("Add Row",540,304,80,25)
GUISetState(@SW_SHOW)
#EndRegion ### END Koda GUI section ###


$TabDummy=GUICtrlCreateDummy()
GUICtrlSetOnEvent(-1,"_tabPressed")
Global $arAccelerators[1][2]=[["{TAB}", $TabDummy]]


__ListViewEditInput_StartUp($Form1)
;Listview hinzufügen (Nur Spalte 1 und 2 darf bearbeitet werden) (doubleclick)
;add listview, only edit col 1 and 2, doubleclick
__ListViewEditInput_AddListview($Form1,$ListView1,"0,1,2")
;2. Listview hginzufügen (Nur Zeile 4 darf bearbeitet werden) (singleClick)
;add second listview, row 4 edited,singleclick
__ListViewEditInput_AddListview($Form1,$ListView1,"All","E")
;ESC zum abbrechen und ENTER zum abschicken initialisieren
;esc to cancel and enter to send
__ListViewEditInput_InitializeKeys($Form1,$arAccelerators)
;registriere Funktion, die aufgerufen wird, wenn ein Feld bearbeitet wurde
;register function, after editing a field
__ListViewEditInput_RegisterFunction($ListView1,"_edited","Changed")
;registriere Funktion, die aufgerufen wird, wenn ein Feld nicht bearbeitet wurde
;register Function, when field not edited
__ListViewEditInput_RegisterFunction($ListView1,"_canceled","Canceled")
;listview ist nicht mehr bearbeitbar
;listview can not be edited anymore
;__ListViewEditInput_DeleteListview($hListView2)


While 1
    $nMsg = GUIGetMsg()
    Switch $nMsg
        Case $Button1
            _SelectFolder()
        Case $Button2
            _fnr()
        Case $Button3
            _AddRow()
        Case $GUI_EVENT_CLOSE
            Exit

    EndSwitch
WEnd


;GUI
#cs
GUICreate("Find And Replace", 1000, 600)
$sourceFolder = GUICtrlCreateInput("Source Folder", 10, 10, 280, 20)
$add = GUICtrlCreateButton("Add", 10, 35, 75, 20)
$mylist = GUICtrlCreateList("", 10, 60, 280, 300)
$Button2=GUICtrlCreateButton("Replace",10,350)
$ListView1=GUICtrlCreateListView("Find|Replace",10,600,850,550,-1)
GUISetState(@SW_SHOW)


While 1
    $msg = GUIGetMsg()
    Switch $msg
        Case $Button1
            _SelectFolder()
        Case $Button2
            _fnr()
        Case $GUI_EVENT_CLOSE
            ExitLoop
    EndSwitch
WEnd

#ce

Func _SelectFolder()
    Global $open=FileSelectFolder("Select Folder","")
    GUICtrlSetData($Input1,$open)
    ;$sFolder = ControlGetText("Automation", "", "Edit1")
    Global $FileList = _FileListToArrayRec($open, "*.*",1,1,1,2)

        If @error = 1 Then
            MsgBox(0, "", "No Folders Found.")
            Exit
        EndIf
        If @error = 4 Then
            MsgBox(0, "", "No Files Found.")
            Exit
        EndIf

        For $i = 1 To $FileList[0]
            GUICtrlSetData($List1, $FileList[$i])
        Next
EndFunc

#cs
Func _fnr()
$find=InputBox("Find","Find")
$replace=InputBox("Replace With", "Replace With")
$time=_Now()
MsgBox(0,"hello",$time)
Local $logfile= $open & "\" & $time & ".log"
MsgBox(0,"hello",$FileList[0])
    For $i=1 To $FileList[0]
        ;MsgBox(0,"hello",$FileList[$i])
    $a=_ReplaceStringInFile($FileList[$i],$find,$replace)
    FileWriteLine($logfile, $find & " was replaced with " & $replace & " in file " & $FileList[$i])
    Next
MsgBox(0,"Test",$a)
EndFunc
#ce


Func _fnr()
    Global $sLog
    ;$find = InputBox("Find", "Find")
    ;$replace = InputBox("Replace With", "Replace With")
    $time = _Now()
    ;$timestr=String($time)
    ;MsgBox(0, "hello", $timestr)
    $count = _GUICtrlListView_GetItemCount($ListView1)
    ;Global $logfile = $open & "\" & $time & ".log"
    Global $sLog = "itworks.log"
    MsgBox(0, "hello", $count)
    For $i=0 to $count
        $find=_GUICtrlListView_GetItemText($ListView1, $i - 1,1)
        $replace=_GUICtrlListView_GetItemText($ListView1, $i - 1,2)
        MsgBox(0,"test", $find & " " & $replace)

            #cs
            For $j = 1 To $FileList[0]
                ;MsgBox(0,"hello",$FileList[$i])
                ;_ReplaceStringInFile($FileList[$i],$find,$replace)
                _ReplaceInFile($sLog, $FileList[$j], $find, $replace)
            Next
            #ce
    Next

    ;MsgBox(0, "Test", $a)
EndFunc   ;==>_fnr

#cs
Func _ReplaceInFile($sLog, $sFile, $sSearch, $sReplace)
    Local $hFile = FileOpen($sFile)
    Local $aLines = FileReadToArray($sFile)
    FileClose($hFile)
    For $i = 0 To UBound($aLines) - 1
        If StringReplace($aLines[$i], $sSearch, $sReplace) Then _
                _FileWriteLog($sLog, $sFile & @TAB & $aLines[$i] & ': ' & $sSearch & ' ==> ' & $sReplace & @CRLF)
    Next
    _FileWriteFromArray($sFile, $aLines)
EndFunc   ;==>_ReplaceInFile
#ce
#cs
Func _ReplaceInFile($sLog, $sFile, $sSearch, $sReplace)
    Local $hFile = FileOpen($sFile)
    Local $aLines = FileReadToArray($sFile)
    ;_ArrayDisplay($aLines)
    FileClose($hFile)
    For $i = 0 To UBound($aLines) - 1
        $aLines[$i]=StringReplace($aLines[$i], $sSearch, $sReplace)
        If @extended Then _FileWriteLog($sLog, $sSearch & " was replaced with " & $sReplace & " in " & $sFile & " at line number " & @TAB & $i  & @CRLF & @CRLF)
    Next
    _FileWriteFromArray($sFile, $aLines)
EndFunc   ;==>_ReplaceInFile
#ce
Func _tabPressed()
    $arLastEdited=__ListViewEditInput_GetEditedCell()
    $count=_GUICtrlListView_GetColumnCount($arLastEdited[0])
    __ListViewEditInput_saveLVChange()
    if $arLastEdited[2]<$count then
        __ListViewEditInput__EditItem($arLastEdited[0],$arLastEdited[1],$arLastEdited[2]+1)
    endif
EndFunc

Func _AddRow()
    GUICtrlCreateListViewItem("|",$ListView1)
EndFunc

The problem is that the code cannot use the find column of the listview to work efficiently. It can read the replace with column. I cannot understand where am I wrong.

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...