Example

Search a File

Author: Carl Sassenrath
Return to REBOL Cookbook

Here's how to search a text file for a specific string.


    file: %doc.txt
    text: read file
    str: find text "web"

The STR now points to the position where the string "web" was found (within the larger text string). If the string is not found, a NONE value is returned.

If you want to print the position where the string was found:


    print index? str

If you want to copy the text you found, add a line like this:


    part: copy/part str 80

This copies 80 characters from where you found the string.

Combining these ideas into a useful example:


    file: %doc.txt
    text: read file
    str: find text "web"
    if str [
        print [index? str  copy/part str 80]
    ]

To find all occurrences of a string, you can use a WHILE loop.


    file: %doc.txt
    text: read file
    while [
        text: find text "web"
    ][
        print [index? text  copy/part text 80]
        text: next text
    ]

The loop will repeat until the FIND returns NONE. Each time the string is found the position (index) is printed. The NEXT at the bottom moves past the current position to avoid an infinite loop.

Note that the code above also works for binary files, just be sure to use the /binary refinement to read the file:


    text: read/binary file

Notes

The FIND function has several refinements that allow you to change the way the search works. For example, you can make it case sensitive (/case) or search for simple patterns (/any).

For example, rather than searching for the string web, you can search for similar strings that have any character in the "e" position:


    text: find/any text "w?b"

The ? matches any character. A * matches any number of characters. (Similar to Unix, DOS, and other shells.) See the FIND function for more information.

It is easy to test your use of FIND from the console.


    text: "REBOL says: Hello world!"
    print find/any text "w*r"

The PARSE function can be used for much more complex types of searches involving pattern matching.


2006 REBOL Technologies REBOL.com REBOL.net