PreviousUpNext

5.5.48  Filter a text file

A frequent requirement is to read a text file, make line by line changes to its contents, and then write the result back.

Suppose you want to convert the contents of file foo.txt to upper case. Here is one solution:

    filename = "foo.txt";
    lines    = file::as_lines filename;
    lines    = map string::to_upper lines;
    file::from_lines filename lines; 

If you suffer from One-Liner Disease, you might write this as

    file::from_lines "foo.txt" (map string::to_upper (file::as_lines "foo.txt"));

Or if you enjoy writing C in Mythryl, you might do

    #!/usr/bin/mythryl
    fd_in  = file::open_for_read "foo.txt";
    fd_out = file::open       "foo.txt.new";
    for (line = file::read_line fd_in;
         line != NULL;
         line = file::read_line fd_in
    ){
        line = string::to_upper (the line);
        file::write (fd_out, line);
    };
    file::close_input fd_in;
    file::close       fd_out;
    winix__premicrothread::file::remove_file "foo.txt";
    winix__premicrothread::file::rename_file { from => "foo.txt.new", to => "foo.txt" };
    exit 0;

As Larry Wall says, any code is ok if it gets the job done before you get fired!

For more ideas on transforming lines as you filter a file, see the section on regular expression recipes.


Comments and suggestions to: bugs@mythryl.org

PreviousUpNext