Applescript: Get filenames in folder without extension

Svish picture Svish · Nov 25, 2010 · Viewed 27.3k times · Source

I can get the names of all files in a folder by doing this:

tell application "Finder"
    set myFiles to name of every file of somePath
end tell

How can I change the strings in myFiles so that they do not include the file extension?

I could for example get {"foo.mov", "bar.mov"}, but would like to have {"foo", "bar"}.


Current solution

Based on the accepted answer I came up with the code below. Let me know if it can be made cleaner or more efficient somehow.

-- Gets a list of filenames from the
on filenames from _folder

    -- Get filenames and extensions
    tell application "Finder"
        set _filenames to name of every file of _folder
        set _extensions to name extension of every file of _folder
    end tell

    -- Collect names (filename - dot and extension)
    set _names to {}
    repeat with n from 1 to count of _filenames

        set _filename to item n of _filenames
        set _extension to item n of _extensions

        if _extension is not "" then
            set _length to (count of _filename) - (count of _extension) - 1
            set end of _names to text 1 thru _length of _filename
        else
            set end of _names to _filename
        end if

    end repeat

    -- Done
    return _names
end filenames

-- Example usage
return filenames from (path to desktop)

Answer

Dan picture Dan · Sep 21, 2012

From http://www.macosxautomation.com/applescript/sbrt/index.html :

on remove_extension(this_name)
  if this_name contains "." then
    set this_name to ¬
    (the reverse of every character of this_name) as string
    set x to the offset of "." in this_name
    set this_name to (text (x + 1) thru -1 of this_name)
    set this_name to (the reverse of every character of this_name) as string
  end if
  return this_name
end remove_extension