代码之家  ›  专栏  ›  技术社区  ›  Petruza

获取脚本上丢弃的文件的文件名

  •  1
  • Petruza  · 技术社区  · 14 年前

    我编写了这个applescript脚本来创建符号链接。
    从中分派 POSIX path of ,如果没有路径,如何获取已删除文件的文件名?

    on open filelist
        repeat with i in filelist
            do shell script "ln -s " & POSIX path of i & " /Users/me/Desktop/symlink"
        end repeat
    end open

    PS:我知道这会期望删除许多文件,并尝试创建多个同名链接,这会导致错误。事实上,我从一个网站上复制了这个例子,由于我对applescript几乎一无所知,我不知道如何在一个文件中完成这项工作,对此的帮助也将不胜感激。

    2 回复  |  直到 14 年前
        1
  •  1
  •   Antal Spector-Zabusky    14 年前

    我不确定你到底想做什么,但我有个猜测。您是否希望获取掉在脚本上的每个文件,并为桌面上的每个文件创建一个符号链接?所以如果我放弃 ~/look/at/me ~/an/example 你将会拥有 ~/Desktop/me ~/Desktop/example ?如果这就是你想要的,那么你就走运了: ln -s <file1> <file2> ... <directory> 就是这样。( 编辑: 尽管您必须注意两个参数的情况。)因此,您的代码可能如下所示:

    -- EDITED: Added the conditional setting of `dest` to prevent errors in the
    -- two-arguments-to-ln case (see my comment).
    
    on quoted(f)
        return quoted form of POSIX path of f
    end quoted
    
    on open filelist
        if filelist is {} then return
        set dest to missing value
        if (count of filelist) is 1 then
            tell application "System Events" to set n to the name of item 1 of filelist
            set dest to (path to desktop as string) & n
        else
            set dest to path to desktop
        end if
        set cmd to "ln -s"
        repeat with f in filelist & dest
            set cmd to cmd & " " & quoted(f)
        end repeat
        do shell script cmd
    end open
    

    注意使用 quoted form of 它用单引号括住它的参数,所以在shell中执行不会有任何有趣的事情。

    如果出于其他原因想获取文件名,则无需向查找程序发出调用;您可以使用系统事件代替:

    tell application "System Events" to get name of myAlias
    

    将返回存储在 myAlias .


    编辑: 如果你想对一个文件做点什么,这很容易。而不是使用 repeat 要遍历每个文件,只需对第一个文件执行相同的操作,由 item 1 of theList . 所以在这种情况下,您可能需要这样的东西:

    -- EDITED: Fixed the "linking a directory" case (see my comment).
    
    on quoted(f)
        return quoted form of POSIX path of f
    end quoted
    
    on open filelist
        if filelist is {} then return
        set f to item 1 of filelist
        tell application "System Events" to set n to the name of f
        do shell script "ln -s " & ¬
            quoted(f) & " " & quoted((path to desktop as string) & n)
    end open
    

    基本上是一样的,但我们把第一件东西 filelist 忽略其余的。另外,在最后,我们显示一个包含符号链接名称的对话框,这样用户就知道刚才发生了什么。

        2
  •  1
  •   markratledge    14 年前

    作为一个例子,您可以使用finder而不是shell脚本来获取单个文件的名称,该文件将被放到保存为应用程序的脚本上。如果不需要“显示”对话框,可以将其删除,但可以将文件名作为变量使用:

    on open the_files
        repeat with i from 1 to the count of the_files
            tell application "Finder"
                set myFileName to name of (item i of the_files)
            end tell
            display dialog "The file's name is " & myFileName
        end repeat
    end open