【发布时间】:2012-07-25 18:39:48
【问题描述】:
我有一个applescript,用户将在其中选择一个文件,我需要得到该文件的名称减去扩展名。
我在另一个网站上发现了一个帖子说这会起作用:
tell application "Finder"
set short_name to name of selected_file
end tell
但它也会返回扩展名。我怎样才能只得到文件名?
【问题讨论】:
标签: applescript
我有一个applescript,用户将在其中选择一个文件,我需要得到该文件的名称减去扩展名。
我在另一个网站上发现了一个帖子说这会起作用:
tell application "Finder"
set short_name to name of selected_file
end tell
但它也会返回扩展名。我怎样才能只得到文件名?
【问题讨论】:
标签: applescript
您可以向 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
【讨论】:
这应该适用于包含句点和没有扩展名的文件名(但不能同时包含两者)。它返回具有多个扩展名的文件的最后一个扩展名。
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
【讨论】:
这是获取文件名的脚本。
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
【讨论】:
此脚本使用 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))
【讨论】: