How to find the first or last occurrence of a string in a text file?
;==========================================================================================================================================
;
; How to find the first or last occurrence of a string in a text file?
;
;
; Utilizing string function "StrIndex (string, sub-string, start, direction)".
;
;------------------------------------------------------------------------------------------------------------------------------------------
; (c)Detlev Dalitz.20101007.
;==========================================================================================================================================

;------------------------------------------------------------------------------------------------------------------------------------------
#DefineSubRoutine udsDisplayResult ()
strMsgTitle = "Search Result"
strMsgText = "Searched for: """ : strSearch : """"
strMsgText = strMsgText : @LF : "Direction: " : ItemExtract (1 + intSearchDirection, "Forward,Backward", ",")
strMsgText = strMsgText : @LF : "Found: " : ItemExtract (1 + !!intPos, "No,Yes", ",")
If !!intPos Then strMsgText = strMsgText : @LF : "At Index: " : intPos
Pause (strMsgTitle, strMsgText)
#EndSubRoutine
;------------------------------------------------------------------------------------------------------------------------------------------


DirChange (DirScript ())

strFileThis = IntControl (1004, 0, 0, 0, 0) ; We use this script as test input file.
strText = FileGet (strFileThis)


; There are four occurrences of the test search string in this script file.
; @$!~# <== This first occurrence will be found by reading forward.


; Test 1. Search direction forward.
strSearch = "@$!~#"
intSearchDirection = @FWDSCAN

; Test 1.1. "Found: Yes."
intPos = StrIndex (strText, strSearch, 0, intSearchDirection)
udsDisplayResult ()

; Test 1.2. "Found: No."
strSearch = strSearch : "." ; Prepare the "not found" case for this example.
intPos = StrIndex (strText, strSearch, 0, intSearchDirection)
udsDisplayResult ()


; Test 2. Search direction backward.
strSearch = "@$!~#"
intSearchDirection = @BACKSCAN

; Test 2.1. "Found: Yes."
intPos = StrIndex (strText, strSearch, 0, intSearchDirection)
udsDisplayResult ()

; Test 2.2. "Found: No."
strSearch = strSearch : "." ; Prepare the "not found" case for this example.
intPos = StrIndex (strText, strSearch, 0, intSearchDirection)
udsDisplayResult ()


; @$!~# <== This last occurrence will be found by reading backward.

:CANCEL
Exit