Sign in to follow this  
Followers 0
alex OF DEATH

Finding a line with specific word...

4 posts in this topic

I need to find the line that contains a word in a .txt file, and have the whole line returned.

I use a fileread() to find the word, but it only returns the word found, which is useless. I need the line It was found on.

Any help/suggestions? It would make this application like, 100 times easier.


Share this post


Link to post
Share on other sites



I need to find the line that contains a word in a .txt file, and have the whole line returned.

I use a fileread() to find the word, but it only returns the word found, which is useless. I need the line It was found on.

Any help/suggestions? It would make this application like, 100 times easier.

In the include file "file.au3", I found _FileReadToArray, which in the middle has this statement:

$aArray = StringSplit(StringStripCR(FileRead($hFile, FileGetSize($sFilePath))), @LF)

Got me thinking that if the file's not too big, you could do something similar with StringRegExp, like:

#include <array.au3>; To show the result (not needed by the function)

$asArray = _FileFindMatchingLines("c:\windows\system.ini", "=")
if IsArray($asArray) then _ArrayDisplay($asArray)

Func _FileFindMatchingLines($sFilePath, $sPattern)
;==============================================
; Local Constant/Variable Declaration Section
;==============================================
    Local $hFile

    $hFile = FileOpen($sFilePath, 0)

    If $hFile = -1 Then
        SetError(1)
        Return 0
    EndIf

    $aArray = StringRegExp(StringStripCR(FileRead($hFile, FileGetSize($sFilePath)) & @LF),"(.*?" & $sPattern & ".*?)\n", 3)

    FileClose($hFile)
    Return $aArray
EndFunc

The only tricky bit is to remember that you're passing a RegExp pattern into the function, so special characters (like * and ?) need to be 'escaped' - see StringRegExp for details.

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