Jump to content

_FindInFile()


LurchMan
 Share

Recommended Posts

Hey everyone -

Below is my version of a find in file program with example. Let me know your thoughts.

#include <file.au3>
#include <array.au3>
 
#region===========Example
$sDir = @ScriptDir & "\test"
$sStringToFind = "you found me!"
 
$sRtn = _FindInFiles ($sDir, $sStringToFind) ;Search all files in dir, not case sensitive
 
If @error Then
    ConsoleWrite("return code: " & $sRtn & " @error: " & @error & @CRLF)
Else
    _ArrayDisplay ($sRtn)
EndIf
#endregion========Example
 
 
; #FUNCTION# ====================================================================================================================
; Name...........: _FindInFiles
; Description ...: Finds a specified string within all (or specified type of) files within a directory
; Syntax.........: _FindInFiles ($sPath, $sFindString[, $sFilter="*"[, $iCase=0]])
; Parameters ....: $sPath   - Directory to look in.
;                 $sFilter - Optional: the filter to use, default is *. Search the Autoit3 helpfile for the word "WildCards" For details.
;                 $iCase   - Optional: specifies whether search string is case sensitive
;                 |$iCase=0(Default) Not case sensitive
;                 |$iCase=1 Case sensitive
; Return values .: Failure: Returns 0 and sets @error:
;                           @error 1 = String not found
;                           @error 2 = No Files found with specified directory with specified file filter
;                 Success: Array containing results (See remarks for array format)
; Author ........: LurchMan
; Modified.......:
; Remarks .......: The array returned is two-dimensional and is made up as follows:
;                               $array[0][0] = Number of results
;                                $array[n][0] = Full path to file
;                               $array[n][1] = Line the search string appears in the file
;                               $array[n][2] = Position on the line
; Related .......:
; Link ..........:
; Example .......: Yes
; Note ..........:
; ===============================================================================================================================
Func _FindInFiles ($sPath, $sFindString, $sFilter="*", $iCase=0)
    Local $aReturn[1][3] = [["0","",""]]
 
    If StringRight ($sPath, 1) <> "\" Then $sPath &= "\"
 
    $aFiles = _FileListToArray ($sPath, $sFilter, 1)
    If @error Then
        SetError (2)
        Return 0
    EndIf
 
    For $iFile = 1 To $aFiles[0]
        $hFile = FileOpen ($sPath & $aFiles[$iFile], 0)
        $sRead = FileRead ($hFile)
        FileClose ($hFile)
 
        If StringInStr ($sRead, $sFindString, $iCase) Then
            $aSplit = StringSplit ($sRead, @LF)
            For $iLine = 1 To $aSplit[0]
                $iPOS = StringInStr ($aSplit[$iLine], $sFindString, $iCase)
                If $iPOS > 0 Then
                    ReDim $aReturn[UBound($aReturn)+1][3]
                    $aReturn[UBound($aReturn)-1][0] = $sPath & $aFiles[$iFile]
                    $aReturn[UBound($aReturn)-1][1] = $iLine
                    $aReturn[UBound($aReturn)-1][2] = $iPOS
                    $aReturn[0][0] = $aReturn[0][0] + 1
                EndIf
            Next
        EndIf
    Next
 
    If $aReturn[0][0] = 0 Then
        SetError(1)
        Return 0
    Else
        Return $aReturn
    EndIf
EndFunc

Dating a girl is just like writing software. Everything's going to work just fine in the testing lab (dating), but as soon as you have contract with a customer (marriage), then your program (life) is going to be facing new situations you never expected. You'll be forced to patch the code (admit you're wrong) and then the code (wife) will just end up all bloated and unmaintainable in the end.

Link to comment
Share on other sites

The function is OK, but a couple of points ... you should point out that it doesn't search in subdirectories and instead of ReDimming everytime by 1 why not reduce the number of ReDim's to multiplying by 2 and checking if a ReDim is required.

- This version can search in subdirectories too by using FindStr & explains how to use Arrays effectively when using the ReDim function in AutoIt, you will see the difference in speed. :graduated:

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

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