italian

Read and write text files with AppleScript
One of the first needings when someone starts programming is the access to tex files.
Let’s see how to do it using AppleScript.

Use the Unix subsytem to read a text file

The easiest way for reading a simple text file is to do it through Unix:

on readFile( unixPath )
return (do shell script "cat '" & unixPath & "'")
end

Obviousley this isn’t the smartest way, in any case we could always consider it.
Other ways, more AppleScriptish, follow.

Use AppleScript to read a text file

The main way uses "open for access":

on readFile( unixPath )
set foo to (open for access (POSIX file unixPath ))
set txt to (read foo for (get eof foo))
close access foo
return txt
end readFile

"open for access" wants a reference to a Finder file, and this is exactly wath we get when using "POSIX file unixPath".

This sintax works fine... but only reads text files "Mac OS Roman" encoded, while often we would like to access UTF-8 or UTF-16 files.

Read a UTF-16 encoded text file:

on readFile( unixPath )
set foo to (open for access (POSIX file unixPath ))
set txt to (read foo for (get eof foo) as Unicode text)
close access foo
return txt
end readFile


Read a UTF-8 encoded text file:

on readFile( unixPath )
set foo to (open for access (POSIX file unixPath ))
set txt to (read foo for (get eof foo) as «class utf8»)
close access foo
return txt
end readFile

Every paragraph of a text

Split a text variable in a list containing one line per entry is quite simple:

set listVariable to every paragraph of textVariable

Obviousley the variable listVariable isn’t linked to the original text, by the way after changing it we can easily rebuild the entire text in a variable::

set textVariable to (listVariable) as text

Search and Replace

AppleScript doesn’t support regular expressions (not out-of-the-box, language modules could extend it), but there’s a simple way for searching and replacing static values in a string::

display dialog( my searchAndReplace("my mommy", "my", "your") )

on searchAndReplace( txt, srch, rpl )
set oldtid to AppleScript's text item delimiters
set AppleScript's text item delimiters to {srch}
set temp to every text item of txt
set AppleScript's text item delimiters to {rpl}
set temp to (temp as string)
set AppleScript's text item delimiters to oldtid
return temp
end searchAndReplace

Sounds weird the first time you look at it, in fact it’s fast and very affordable.

To be continued...

...

To be continued...