AppleScript: How to get the character count of an .rtf file

applescriptinternationalizationtext;

I would like an AppleScript .scpt file to determine the character count of any given .rtf file. I'm not sure if this is standard for character counts, but I would like each space character (" ") to also count as one character.

I would like the script to accomplish this, without actually opening the file in TextEdit.

It is important to note that this is a rich text file, not a simple plain text (.txt) file. This fact complicates things. It is not as simple as chopping off the rich text header, because a single .rtf file may contain multiple different types of rich text formatting.

What is the best way to go about this?

Best Answer

You asked, "What is the best way to go about this?" and while I'll not make that determination, nonetheless, here's an example using the do shell script command and some command line utilities.

set theRichTextFile to quoted form of "/path/to/filename.rtf"
set theCharacterCount to do shell script "textutil -stdout -convert txt " & theRichTextFile & " | LANG=en_US.UTF-8 wc -m | sed 's/ //g'"

Note that theRichTextFile must be a quoted POSIX pathname.

Update: Per comment by @jackjr300, added LANG=en_US.UTF-8 to the command.