user1220109
user1220109

Reputation: 131

Applescript to get file name without extension

I have an applescript where the user will pick one file and i need to get the name of that file minus the extension.

I found a post on a different site that said this would work:

tell application "Finder"
    set short_name to name of selected_file
end tell

But it returns the extensions as well. How can I get just the name of the file?

Upvotes: 4

Views: 11820

Answers (4)

user866649
user866649

Reputation:

You can ask the Finder or System Events for the name extension and remove that part from the full name. This will also avoid issues with names that have periods in them or extensions that may not be what you think they are.

set someItem to (choose file)

tell application "System Events" to tell disk item (someItem as text) to set {theName, theExtension} to {name, name extension}
if theExtension is not "" then set theName to text 1 thru -((count theExtension) + 2) of theName -- the name part

log theName & tab & theExtension

Upvotes: 4

adayzdone
adayzdone

Reputation: 11238

This script uses ASObjC Runner to parse file paths. Download ASObjC Runner here.

set aFile to choose file
tell application "ASObjC Runner" to set nameS to name stub of (parsed path of (aFile as text))

Upvotes: 0

Lri
Lri

Reputation: 27613

This should work with filenames that contain periods and ones that don't have an extension (but not both). It returns the last extension for files that have multiple extensions.

tell application "Finder"
    set n to name of file "test.txt" of desktop
    set AppleScript's text item delimiters to "."
    if number of text items of n > 1 then
        set n to text items 1 thru -2 of n as text
    end if
    n
end tell

name extension also returns the last extension for files with more than one extension:

tell application "Finder"
    name extension of file "archive.tar.gz" of desktop -- gz
end tell

Upvotes: 2

Raoul Grösser
Raoul Grösser

Reputation: 116

Here's the script for getting just the filenames.

set filesFound to {}
set filesFound2 to {}
set nextItem to 1

tell application "Finder"
  set myFiles to name of every file of (path to desktop) --change path to whatever path you want   
end tell

--loop used for populating list filesFound with all filenames found (name + extension)
repeat with i in myFiles
  set end of filesFound to (item nextItem of myFiles)
  set nextItem to (nextItem + 1)
end repeat

set nextItem to 1 --reset counter to 1

--loop used for pulling each filename from list filesFound and then strip the extension   
--from filename and populate a new list called filesFound2
repeat with i in filesFound
  set myFile2 to item nextItem of filesFound
  set myFile3 to text 1 thru ((offset of "." in myFile2) - 1) of myFile2
  set end of filesFound2 to myFile3
  set nextItem to (nextItem + 1)
end repeat

return filesFound2

Upvotes: 0

Related Questions