user3101259
user3101259

Reputation: 91

Selecting POSIX file based on file name

I'm having trouble accessing this file while trying to select it on the beginning characters basis...

set location to "/Users/myuser/Desktop/"
set bom to POSIX file (location & (first file of location whose name begins with "thisFile"))
tell application "Preview" to open bom

is it path/alias vs text type of a thing?

Upvotes: 1

Views: 284

Answers (2)

mklement0
mklement0

Reputation: 437080

vadian's answer works well, but it's worth mentioning that:

  • you can get access to well-known folders even in the default context, outside the context of System Events and Finder; e.g.:

    • path to desktop
    • path to home folder
    • Use, e.g., POSIX path of (path to home folder) to get the POSIX path.
  • using context System Events is usually preferable to the Finder context, for reasons of both performance and predictability.

With an arbitrary target folder, using a POSIX path:

tell application "System Events"
  set targetFolder to alias "/Users/jdoe/Desktop"
  # equivalent of: set targetFolder to (path to desktop)
  set targetFile to first file of targetFolder whose name starts with "thisFile"
end tell

tell application "Preview" to open targetFile

Alternatively, if you know your way around the shell, you could try:

set targetFilePosixPath to do shell script "fls=(~/Desktop/*.pdf); printf %s \"$fls\""
tell application "Preview" to open (POSIX file targetFilePosixPath as alias)

Upvotes: 1

vadian
vadian

Reputation: 285059

Only System Events and the Finder know what a file in the file system is.
The Finder has a property desktop which points always to the desktop of the current user.

tell application "Finder" to set bom to first file of desktop whose name begins with "thisFile"
tell application "Preview" to open (bom as alias)

Or with an arbitrary POSIX path

set location to POSIX file "/Users/myuser/Desktop" as text
tell application "Finder" to set bom to first file of folder location whose name begins with "thisFile"
tell application "Preview" to open (bom as alias)

The alias coercion is needed because Preview doesn't recognize Finder file specifier objects.

Upvotes: 1

Related Questions