Example

Replace Text in a File

Author: Carl Sassenrath
Return to REBOL Cookbook

Here's how to search and replace text in file.


    file: %doc.txt
    text: read file
    replace text "web" "rebol"
    write file text

To replace all occurances add the /all refinement:


    replace/all text "web" "REBOL"

To make the search case sensitive add the /case refinement:


    replace/case/all text "Web" "REBOL"

This code will replace the string in all the text files found in your current directory:


    foreach file read %./ [
        if find [%.txt %.text] suffix? file [
            text: read file
            replace/all text "web" "rebol"
            write file text
        ]
    ]

You can add additional file suffixes if necessary. (Just be sure they are for text files. If you use this code on binary files, they will be corrupted.)

Shortcut

It is common practice in REBOL to remove extra code. The above example could also be written:


    foreach file read %./ [
        if find [%.txt %.text] suffix? file [
            write file replace/all read file "web" "rebol"
        ]
    ]


2006 REBOL Technologies REBOL.com REBOL.net