Le risposte alle domande sul Mac

AppleScript: read and write text files

Main topics: ResourcesMacGuides

Argomenti: Applescript

Author: Marco Balestra

When starting with programming one of the firt issue is the access to text 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 is “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" requires 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 encoded “Mac Roman”, while often we needto access Unicode (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

Of course 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 single 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

I know, it sounds weird the first time you look at it…
On the other hand it’s fast and very affordable.

Powered by JBLOUD, © 2021 altersoftware.IT