Sign in to follow this  
Followers 0

[Solved] Search string in multiple files

5 posts in this topic

#1 ·  Posted (edited)

I am trying to find all the .txt or files with specific extension and load the file path to array using "_FileListToArrayEx". The result was success and pretty good. I removed first row as it contain only number. The remaining array only contain link to files.

secondly, I have got a list of strings in a different array set with following content

$array[0] = string1

$array[1] = string2

$array[2] = string3

$array[3] = string4

$array[n] = stringn

Now what i am trying to do is search each content of array through all the files. If the match is found then write the particular arry to the different .txt file. Here is the _FileListToArrayEx UDF i used for finding files with specific extension :-

; #FUNCTION# ========================================================================================================================
; Name...........: _FileListToArray
; Description ...: Lists files and\or folders in a specified path (Similar to using Dir with the /B Switch)
; Syntax.........: _FileListToArray($sPath[, $sFilter = "*"[, $iFlag = 0]])
; Parameters ....: $sPath - Path to generate filelist for.
;                $sFilter - Optional the filter to use, default is *. (Multiple filter groups such as "All "*.png|*.jpg|*.bmp") Search the Autoit3 helpfile for the word "WildCards" For details.
;                $iFlag - Optional: specifies whether to return files folders or both Or Full Path (add the flags together for multiple operations):
;                |$iFlag = 0 (Default) Return both files and folders
;                |$iFlag = 1 Return files only
;                |$iFlag = 2 Return Folders only
;                |$iFlag = 4 Search subdirectory
;                |$iFlag = 8 Return Full Path
; Return values .: @Error - 1 = Path not found or invalid
;                |2 = Invalid $sFilter
;                |3 = Invalid $iFlag
;                |4 = No File(s) Found
; Author ........: SolidSnake <MetalGX91 at GMail dot com>
; Modified.......:
; Remarks .......: The array returned is one-dimensional and is made up as follows:
;                            $array[0] = Number of Files\Folders returned
;                            $array[1] = 1st File\Folder
;                            $array[2] = 2nd File\Folder
;                            $array[3] = 3rd File\Folder
;                            $array[n] = nth File\Folder
; Related .......:
; Link ..........:
; Example .......: Yes
; Note ..........: Special Thanks to Helge and Layer for help with the $iFlag update speed optimization by code65536, pdaughe
;                Update By DXRW4E
; ===================================================================================================================================
Func _FileListToArrayEx($sPath, $sFilter = "*", $iFlag = 8)
    Local $hSearch, $sFile, $sFileList, $iFlags = StringReplace(BitAND($iFlag, 1) + BitAND($iFlag, 2), "3", "0"), $sSDir = BitAND($iFlag, 4), $FPath = "", $sDelim = "|", $sSDirFTMP = $sFilter
    $sPath = StringRegExpReplace($sPath, "[\\/]+\z", "") & "\" ; ensure single trailing backslash
    If Not FileExists($sPath) Then Return SetError(1, 1, "")
    If BitAND($iFlag, 8) Then $FPath = $sPath
    If StringRegExp($sFilter, "[\\/:><]|(?s)\A\s*\z") Then Return SetError(2, 2, "")
    If Not ($iFlags = 0 Or $iFlags = 1 Or $iFlags = 2 Or $sSDir = 4 Or $FPath <> "") Then Return SetError(3, 3, "")
    $hSearch = FileFindFirstFile($sPath & "*")
    If @error Then Return SetError(4, 4, "")
    Local $hWSearch = $hSearch, $hWSTMP = $hSearch, $SearchWD, $sSDirF[3] = [0, StringReplace($sSDirFTMP, "*", ""), "(?i)(" & StringRegExpReplace(StringRegExpReplace(StringRegExpReplace(StringRegExpReplace(StringRegExpReplace(StringRegExpReplace("|" & $sSDirFTMP & "|", '\|\h*\|[\|\h]*', "\|"), '[\^\$\(\)\+\[\]\{\}\,\.\]', "\\$0"), "\|([^\*])", "\|^$1"), "([^\*])\|", "$1\$\|"), '\*', ".*"), '^\||\|$', "") & ")"]
    While 1
        $sFile = FileFindNextFile($hWSearch)
        If @error Then
            If $hWSearch = $hSearch Then ExitLoop
            $hWSearch -= 1
            $SearchWD = StringLeft($SearchWD, StringInStr(StringTrimRight($SearchWD, 1), "\", 1, -1))
        ElseIf $sSDir Then
            $sSDirF[0] = @extended
            If ($iFlags + $sSDirF[0] <> 2) Then
                If $sSDirF[1] Then
                    If StringRegExp($sFile, $sSDirF[2]) Then $sFileList &= $sDelim & $FPath & $SearchWD & $sFile
                    $sFileList &= $sDelim & $FPath & $SearchWD & $sFile
            If Not $sSDirF[0] Then ContinueLoop
            $hWSTMP = FileFindFirstFile($sPath & $SearchWD & $sFile & "\*")
            If $hWSTMP = -1 Then ContinueLoop
            $hWSearch = $hWSTMP
            $SearchWD &= $sFile & "\"
            If ($iFlags + @extended = 2) Or StringRegExp($sFile, $sSDirF[2]) = 0 Then ContinueLoop
            $sFileList &= $sDelim & $FPath & $sFile
    If Not $sFileList Then Return SetError(4, 4, "")
    Return StringSplit(StringTrimLeft($sFileList, 1), "|")

and here is the code i used for deleting first row :-

For $n = UBound($array) - 1 to 0 step -1
    If IsInt ($array[$n]) Then ;= "2" Then
     _ArrayDelete($array, $n)

I am struck hereater. Any help is appriciated.

Meanwhile i used _FindinFile UDF written by guinness, but it did not give me any output. Attached screenshot shows the result of _FinfinFile. Even this UDF solution will also solve half of my

Edited by sundar

Share this post

Link to post
Share on other sites

The link which you gave is again for listing files which i have already done it. I need to find if string in array exist in the files.

Share this post

Link to post
Share on other sites

Just wanted to share you all that _FinfInFile is working now. The preoblem was with forum formating. I copied fresh function and it is working now.

Though remaining questions not solved.

Share this post

Link to post
Share on other sites


_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_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: 04/09/2015

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  
Followers 0

  • Similar Content

    • cheeroke
      By cheeroke
      Hi all,
      I got this code and would like to be able to change Baud Rate and instead of sending character by character i would like to be able (if possible) to send whole string. But i don't know how to change it.
      I am taking input from file and processing whole line (this is done in FilesHandling.au3).
      To execute this i am just calling SendData("FileName", int) in "main" script.
      Any help very appreciated.
      #include <WinAPI.au3> #include <Array.au3> #include "FilesHandling.au3" ;init DLL function, we need handle to call the function $h = DllCall("Kernel32.dll", "hwnd", "CreateFile", "str", "\\.\COM19", "int", BitOR($GENERIC_READ,$GENERIC_WRITE), "int", 0, "ptr", 0, "int", $OPEN_EXISTING, "int", $FILE_ATTRIBUTE_NORMAL, "int", 0) $handle=$h[0] Func SendData($FileName, $LineNumber) ;string to be send $c = readFile($FileName, $LineNumber) $cLenght = StringLen($c) $aArray = StringSplit($c, "") ;_ArrayDisplay($aArray, "", Default, 64) For $i = 1 To $cLenght writeChar($handle, $aArray[$i], $cLenght) Next ;move to next line writeChar($handle, @CR,1) EndFunc ;write a single char func writeChar($handle,$c,) $stString = DLLStructCreate("char str") $lpNumberOfBytesWritten = 0 DllStructSetData($stString, 1, $c) $res = _WinAPI_WriteFile($handle, DllStructGetPtr($stString, "str"), 1,$lpNumberOfBytesWritten) if ($res<>true) then ConsoleWrite ( _WinAPI_GetLastErrorMessage() & @LF) EndIf EndFunc  
    • FroVN
      By FroVN
      Hi, i have a problem :" can't set the name of file with a special character like: \;/;";|;...  have anyway to short the StringInSrt and Stringreplace? i am using this code but too long
         if StringInStr($title,'\') or StringInStr($title,'/') or StringInStr($title,':') or StringInStr($title,'*') or StringInStr($title,'?') or StringInStr($title,'"') or StringInStr($title,'<') or StringInStr($title,'>') or StringInStr($title,'|') Then
    • algiuxas
      By algiuxas
      Hello everybody, so I might found a bug in _ArraySearch:
      #include <Array.au3> Local $abc[2] = ["b", "b"] $h = "+---------------------------------+" & @CRLF ConsoleWrite($h) For $i = 0 To 1 $abc[0] = 0 out() $abc[0] = 1 out() $abc[0] = -1 out() $abc[0] = "Abc" out() $abc[1] = "Hello" Next Func txt() Return "$abc = [" & $abc[0] & ", " & $abc[1] & "]" & @CRLF & _ "> _ArraySearch($abc,""Hello"") = " EndFunc ;==>txt Func shouldoutput($ans) Return "_ArraySearch Should return: " & ($ans ? 1 : -1) EndFunc ;==>shouldoutput Func out() ConsoleWrite("> " & txt() & _ArraySearch($abc, "Hello") & @CRLF & "> " & shouldoutput($abc[1] == "Hello") & @CRLF & $h) EndFunc ;==>out Exit Sorry for this messy script
    • wakillon
      By wakillon
      Mp3SearchEngine v2.0.0.6

      May be some of you know Songr .
      This script do the same job, it can find more mp3 files but is not as fast as Songr.

      Sites used are music search engine Websites designed for LEGAL entertainment purposes only.
      Thanks to Brett Francis, Prog@ndy and Eukalyptus for >Bass Udf, trancex for >WinHttp Udf and the AutoIt Community for his help.

      Changes of v1.0.8.5
      Three websites replaced cause they are dead or use now js.
      All search engines updated ( not without difficulties for audiodump)
      I use RAGrid.dll for the first listview (more fast and stable, but with some inconvenients to manage the no-edit of cells)
      Input queries are saved ( the twenty latest)
      I use now an mp3 pre-Load management before playing and a double progressbar for visualize pre-load and play, where you can click for directly go play in the loaded part.
      Most includes needed are embedded and all external files are embedded in script with >BinaryToAu3Kompressor .
      Multi downloads available with embedded downloader.exe
      Changes of v1.0.8.8
      Search on audiodump and myfreemp3 fixed.
      New buttons.
      Added Gui Menu.
      Titles are no more editable.
      New "About" with >TaskDialog (Thanks Prog@andy)
      Query button permit now to check / uncheck all checkboxes
      And some few fixes and cleaning.
      Really more stable now.
      Changes of v1.0.9.2
      Dilandau is replaced by mp3chief and mp3ili by mp3clan 
      Search on mp3juices, baseofmp3 and soundcloud fixed.
      Soso now provide m4a (aac) instead of mp3 ( m4a can be played by MSE)
      Added possibility to encode automaticaly to mp3, aac or ogg ( at the end of download) using bassenc.dll and command line tools : lame, faac and oggenc.
      Changes of v1.0.9.3   mp3skull fixed mp3chief fixed myfreemp3 fixed mp3clan changed to tusmp3  mp3juices changed to emp3world baseofmp3 changed to imp3 and some minor improvements.  
      Most previous websites used are dead or have changed the way to get links, 
      so instead of try to repair the previous version, i have created a complete new version.
      The main tendency is the simplification :
      Only one website : audiodump (Up to 500 results by request)
      Script use now the little pearl created by Ward : curl.au3
      It permit to create tasks (get source and get multi mp3) in asynchronous mode.
      So now, no need to use several executables and no more gui who do not respond in case of connection problems. 
      Script use Bass.dll X86 loaded in memory for play songs.
      Result is light and fast, but don't abuse of audiodump servers who are not beasts of race.
      Warning : For avoid errors with curl.au3, you'll need to comment the line 63 : ;~ #Include <BinaryCall.au3>
      @AutoItX64 not supported and only tested on Win7X64 and Win8.1X64.
      As your browser, use Ctrl+w for remove the current Tab.(if there is no search or download running from it)
      And also Ctrl+q for set/remove Gridlines.
      Events are displayed to the bottom of the Gui.
      Added a Paste Button.
      Querry list is now correctly saved.
      Querry Combo is now sorted in alphabetical order
      After a 'No match', the next search will use the previous empty listview.
      Bug when removing tabs is corrected.
      Added string correction for the request that, in the previous version, was not always able to return a correct result.
      A big thanks to Ward for his great UDF, and Nina my favorite tester, (who between us is also my third daughter), for his precious advices .
      previous downloads : 1703
      As there is no more script downloads count, source and executable are available in the downloads section

      Enjoy ! 
      July 2017 Project Discontinued due to website changes
    • usmiv4o
      By usmiv4o
      #cs ---------------------------------------------------------------------------- AutoIt Version: Author: usmiv4o Script Function: AutoIt script to check if files in directory are changed. It is usefull for security contra-inteligense measures. Function Name: LoadTripwireDB() Description: Loads database (text file tripwire.txt) and compare files in /test folder for changes. compares Hash (MD5) checksums. If they are not the same starts Initial() Function Name: Initial() Description: Checks directory and makes index of files and their MD5 checksums in text file (tripwire.txt) Function Name: Hush() Description: Checks file and returns its MD5 checksum. Requirement(s): Windows XP Return Value(s): On Success - Returns true. Files are the same as before. On Failure - return false. Example: LoadTripwireDB() #ce ---------------------------------------------------------------------------- #include <Crypt.au3> #include <File.au3> #include <Array.au3> $sDir = @ScriptDir & "\Test" $sFilePath = @ScriptDir & "\tripwire.txt" Func Hush(ByRef $sFile) $sRead = FileOpen( $sFile) $dHash = _Crypt_HashData($sRead, $CALG_MD5) ; Create a hash of the text entered. ConsoleWrite("Hash of file " & $sFile & " is " & $dHash & @CRLF) EndFunc ;ConsoleWrite("Files in Dir are " & $aScriptDir[0] & @CRLF) ;$sFilePath = @ScriptDir & "\Examples.txt" ;_FileWriteFromArray($sFilePath, $aScriptDir, 1) ;_ArrayDisplay($aScriptDir, "1D display") Func Initial() $aScriptDir = _FileListToArray($sDir) for $i = 1 To UBound($aScriptDir) - 1 $dHash = _Crypt_HashData($i, $CALG_MD5) ;ConsoleWrite("File " & $aScriptDir[$i] & " is " & $dHash & @CRLF) ConsoleWrite($aScriptDir[$i] & ":" & $dHash & @CRLF) ;Hush($aScriptDir[$i]) ;FileWrite $hFileOpen = FileOpen($sFilePath, $FO_APPEND) If $hFileOpen = -1 Then MsgBox($MB_SYSTEMMODAL, "", "An error occurred when reading the file.") EndIf FileWrite($hFileOpen, $aScriptDir[$i] & ":" & $dHash & @CRLF) Next EndFunc Func Monitor() $aScriptDir = _FileListToArray($sDir) for $i = 1 To UBound($aScriptDir) - 1 Next EndFunc Func LoadTripwireDB() $comparison_ok = false $dArray = _FileListToArray($sDir) ;directory $dArray0 = UBound($dArray) - 1 $fArray = FileReadToArray($sFilePath) ;file $fArray0 = UBound($fArray) ;_ArrayDisplay($dArray, "files array") if $dArray0 = $fArray0 Then ; are file same as recorded in txt file? ;ConsoleWrite("files in monitoring dir: " & $dArray[0] & " = file recorded: " & $fArray0 & @CRLF & $fArray[0]& @CRLF) for $i = 1 To UBound($dArray) - 1 ;ConsoleWrite("i = " & $i & @CRLF) $dHash = _Crypt_HashData($i, $CALG_MD5) ;binary ;$dHash = BinaryToString($dHash) $ffhash = StringSplit( $fArray[$i-1],":") $fhash = $ffhash[2] ;ConsoleWrite("IsBinary $dHash " & IsBinary($dHash) & @CRLF) if $dHash = $fhash Then ;if compared hashes are equal ;ConsoleWrite($fhash & ":" & $dHash & " equal" & @CRLF) ;ConsoleWrite("File: " & $fhash & @CRLF & "Directory: " & $dHash & @CRLF & "equal: yes " & @CRLF) Else ;if compared hashes are not equal ;ConsoleWrite("File: " & $fhash & @CRLF & "Directory: " & $dHash & @CRLF & "equal: not " & @CRLF) ;MsgBox(0,"hash md5",$fhash & ":" & $dHash & " not equal") EndIf Next ;ConsoleWrite("hashes are equal" & @CRLF) $comparison_ok = true Else ConsoleWrite("number of files in monitoring dir are not same as recorded" & @CRLF) ConsoleWrite("directory: " & $dArray[0] &":"& "files: " & UBound($fArray) - 1 & @CRLF) EndIf Return $comparison_ok EndFunc #main if LoadTripwireDB() = true Then ConsoleWrite(" hashes are equal " & @CRLF) ElseIf LoadTripwireDB() <> true Then ConsoleWrite(" hashes are not equal " & @CRLF) ConsoleWrite(" hashes are not equal " & @CRLF) Initial() EndIf