alex OF DEATH Posted July 3, 2007 Posted July 3, 2007 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.
Siao Posted July 3, 2007 Posted July 3, 2007 $filename = "somefile.txt" $word = "blah" $h = FileOpen($filename, 0) Do $line = FileReadLine($h) If @error = -1 Then ExitLoop If StringInStr($line, $word) > 0 Then ConsoleWrite($line & @CRLF) Until 0 FileClose($h) "be smart, drink your wine"
MisterBates Posted July 3, 2007 Posted July 3, 2007 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. [u]MisterBates[/u]_____________________________________________________Suspend/Resume Windows ScreensaverWatchWindows - Window watcher/loggerUDF: Click systray menu/submenu itemsUDF: Outlook Express Folder/Message handling (+ example code)HowTo: Multiple icons in one compiled script
alex OF DEATH Posted July 3, 2007 Author Posted July 3, 2007 $filename = "somefile.txt" $word = "blah" $h = FileOpen($filename, 0) Do $line = FileReadLine($h) If @error = -1 Then ExitLoop If StringInStr($line, $word) > 0 Then ConsoleWrite($line & @CRLF) Until 0 FileClose($h) Genius. (Not really, I'm just an idiot) Thanks
Recommended Posts
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 accountSign in
Already have an account? Sign in here.
Sign In Now