【问题标题】:Applescript to get file name without extensionApplescript获取不带扩展名的文件名
【发布时间】:2012-07-25 18:39:48
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: applescript


    【解决方案1】:

    您可以向 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
    

    【讨论】:

    • 这是最干净的方法,告诉 finder 做某事有很多固有的问题
    【解决方案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
    

    【讨论】:

    • 不要忘记将文本项分隔符设置为原始值...将 oldDelims 设置为 AppleScript 的文本项分隔符 将 AppleScript 的文本项分隔符设置为“.” (* 在此处进行处理 *) 将 AppleScript 的文本项分隔符设置为 oldDelims
    【解决方案3】:

    这是获取文件名的脚本。

    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
    

    【讨论】:

    • 如果文件名本身包含句点,脚本当前返回第一个句点之前的部分。
    【解决方案4】:

    此脚本使用 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))
    

    【讨论】:

      猜你喜欢
      • 2011-06-15
      • 2011-10-02
      • 2015-05-13
      • 2011-05-15
      • 2011-05-25
      • 2015-05-20
      • 1970-01-01
      相关资源
      最近更新 更多