4

我有一个applescript,用户将在其中选择一个文件,我需要获取该文件的名称减去扩展名。

我在另一个网站上发现了一个帖子说这会起作用:

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

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

4

4 回答 4

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
于 2012-07-26T00:25:44.647 回答
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
于 2012-07-25T20:07:45.497 回答
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
于 2012-07-25T18:45:02.063 回答
0

该脚本使用 ASObjC Runner 来解析文件路径。在此处下载 ASObjC Runner。

set aFile to choose file
tell application "ASObjC Runner" to set nameS to name stub of (parsed path of (aFile as text))
于 2012-07-25T21:14:24.627 回答