REBOL 3 Docs Guide Concepts Functions Datatypes Errors
  TOC < Back Next >   Updated: 6-Feb-2009 Edit History  

REBOL 3 Concepts: Files: Blocks of Lines

Pending Revision

This document was written for R2 and has yet to be revised for R3.

Text files can be easily accessed and managed as individual lines of text, rather than as a single series of characters. For example, to read a file as a block of lines:

lines: read/lines %service.txt

The above example returns a block containing a series of strings (one for each line) without line terminators. Empty lines are represented by empty strings.

To print a specific line you use the following code:

print first lines
print last lines
print pick lines 100
print lines/500

To print all of the lines of a file, use the following line of code:

foreach line lines [print line]
I wanted the gold, and I sought it,
I scrabbled and mucked like a slave.
Was it famine or scurvy -- I fought it;
I hurled my youth into a grave.
I wanted the gold, and I got it --
Came out with a fortune last fall, --
Yet somehow life's not what I thought it,
And somehow the gold isn't all.

To print all of the lines that contain the string gold, use the following line of code:

foreach line lines [
   if find line "gold" [print line]
]
I wanted the gold, and I sought it,
I wanted the gold, and I got it --
And somehow the gold isn't all.

You can write the text file out as lines using the write function:

write/lines %output.txt lines

To write out specific lines from a block, use:

write/lines %output.txt [
    "line one"
    "line two"
    "line three"
]

In fact, the functions read/lines and write/lines can be combined to process files one line at a time. For example the following code removes all of the comments from a REBOL script:

script: read/lines %script.r
foreach line script [
    where: find line ";"
    if where [clear where]
]
write/lines %script1.r script

Files can be read as lines from a network as well:

data: read/lines http://www.rebol.com

print pick (read/lines ftp://ftp.rebol.com/test.txt) 3
new

The /lines refinement can be used with the open function to read a line at a time from console input. See the chapter on ports for more information.

In addition /lines can be used with /append to append lines from a block to a file.


  TOC < Back Next > REBOL.com - WIP Wiki Feedback Admin