2010-05-26 67 views
1

我使这个Applescript脚本创建了符号链接。
Appart从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的任何事情,我不知道如何为单个文件做这件事,在这方面的帮助也将不胜感激。

回答

1

我不知道你想做什么精确,但我有一个猜测。是否想让每个文件都放在脚本上并为桌面上的每个文件创建一个符号链接?因此,如果我放弃~/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中执行并不会做任何有趣的事情。

如果由于其他原因想要查看文件名称,则不需要调用Finder;您可以使用系统事件,而不是:

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而忽略其他。另外,最后,我们显示一个包含符号链接名称的对话框,以便用户知道刚发生的事情。

+0

Thiks,我真正想要做的是为一个文件。我使用重复,因为我从一个网站得到这个例子,并不知道如何修改它的单个文件。 – Petruza 2010-05-26 22:50:09

+0

编辑:它适用于文件,但它对文件夹失败,这是我最想要的。错误信息是:“In:/ Users/petruza/Desktop /:File exists”桌面上没有与原始文件名称相同的文件,这适用于常规文件,因此路径是正确的。看起来,当获取文件夹放在脚本上时,它将它解释为'/',这是在错误消息中添加到桌面路径上的内容。如果向路径添加尾部斜线,则该错误会显示两个尾部斜线。 – Petruza 2010-05-28 14:47:12

+1

我认为如果我自己学习applescript会更好。你能推荐一个好的教程吗? – Petruza 2010-05-28 14:49:22

1

作为一个例子,您可以使用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