Applescript获取没有扩展名的文件名

时间:2012-07-25 18:39:49

标签: applescript

我有一个苹果脚本,用户将选择一个文件,我需要获取该文件的名称减去扩展名。

我在另一个网站上发现了一条帖子,说这会有效:

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

但它也会返回扩展名。我怎样才能得到文件的名称?

4 个答案:

答案 0 :(得分:4)

您可以向 Finder 系统事件询问名称扩展名,并从全名中删除该部分。这也可以避免在其中包含句点的名称或可能不是认为的扩展名的问题。

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

答案 1 :(得分:2)

这适用于包含句点的文件名和没有扩展名的文件名(但不包括两者)。它返回具有多个扩展名的文件的最后一个扩展名。

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也会返回具有多个扩展名的文件的最后一个扩展名:

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

答案 2 :(得分:0)

这是获取文件名的脚本。

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

答案 3 :(得分:0)

此脚本使用ASObjC Runner来解析文件路径。下载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))