The easiest way to read a textfile is to use the file::as_lines library function, which returns the contents of the file as a list of lines:
#!/usr/bin/mythryl foreach (file::as_lines "my-script") {. print #line; };
When run, this script prints itself out, unsurprisingly enough:
linux$ ./my-script #!/usr/bin/mythryl foreach (file::as_lines "my-script") {. print #line; }; linux$
Similarly, the easiest way to write a textfile is to use the file::from_lines library function:
#!/usr/bin/mythryl file::from_lines "foo.txt" [ "abc\n", "def\n", "ghi\n" ];
Running this from the commandline creates a three-line file named foo.txt:
linux$ ./my-script linux$ cat foo.txt abc def ghi linux$
The easiest way to modify a textfile is just to combine the above two operations. Suppose, for example, that like Will Strunk (of The Elements of Style fame), you detest the word “utilize” and believe replacing it with “use” is always an improvement.
Use your favorite text editor to create a file named foo.txt containing the following text:
Will Strunk never used "utilize"; he always utilized "use".
Here is a script which will change "utilize" to "use" throughout that file:
#!/usr/bin/mythryl fun fix_line( line ) = { regex::replace_all ./utilize/ "use" line; }; lines = file::as_lines "foo.txt"; lines = map fix_line lines; file::from_lines "foo.txt" lines;
And here it is in action:
linux$ cat foo.txt Will Strunk never used "utilize"; he always utilized "use". linux$ ./my-script linux$ cat foo.txt Will Strunk never used "use"; he always used "use". linux$
If you like one-liners, here is a one-line version of the above script:
#!/usr/bin/mythryl file::from_lines "foo.txt" (map (regex::replace_all ./utilize/ "use") (file::as_lines "foo.txt"));
The easiest way to get the names of the files in the current directory is to use dir::files:
linux$ my eval: foreach (dir::files ".") {. printf "%s\n" #filename; }; my-script foo.txt eval: ^D linux$
The easiest way to get the names of all the files in the
current directory or any directory under it is to replace
dir::files by
dir_tree::files in the above script.