Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applescript: Get filenames in folder without extension

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)
like image 967
Svish Avatar asked Nov 25 '10 15:11

Svish


1 Answers

Single line way of doing it, no Finder, no System Events. So more efficient and faster. Side effect (could be good, or bad): a file name ending with "." will have this character stripped out. Using "reverse of every character" makes it works if the name as more than one period.

set aName to text 1 thru ((aName's length) - (offset of "." in ¬
    (the reverse of every character of aName) as text)) of aName

The solution as a handler to process a list of names:

on RemoveNameExt(aList)
    set CleanedList to {}
    repeat with aName in aList
        set the end of CleanedList to text 1 thru ((aName's length) - (offset of ¬
            "." in (the reverse of every character of aName) as text)) of aName
    end repeat
    return CleanedList
end RemoveNameExt
like image 183
Jean.O.matiC Avatar answered Oct 10 '22 23:10

Jean.O.matiC