目前我有一个Applescript执行以下操作:
但是,如果在移动发生之前指定名称的对话框弹出会更好,因此不会先复制原始文件然后重命名。谁能帮助我如何实现这个目标?
property y : POSIX file "/Users/thijmendam/Documents/Newfile/Naamloos.txt" as alias
tell application "Finder"
set x to target of window 1 as alias
duplicate y to x
set name of file "Naamloos.txt" of folder x to the text returned of (display dialog "Rename" default answer "")
end tell
答案 0 :(得分:0)
这应该这样做:
property y : POSIX file "/Users/thijmendam/Documents/Newfile/Naamloos.txt" as alias
tell application "Finder"
set x to target of window 1 as alias
set newFileName to text returned of (display dialog "Rename" default answer "")
set name of (duplicate y to x with replacing) to newFileName
end tell
我添加了with replacing
以防止在该名称的文件已存在时引发错误。你可以删除它,或者只是添加一个try...on error...end try
错误捕获块来满足这种情况。
Terminal 命令cp
也可用于从命令行复制文件。这会将文件 myfile.ext 从桌面复制到Documents文件夹而不重命名:
cp ~/Desktop/myfile.ext ~/Documents/
这将一次复制并重命名该文件:
cp ~/Desktop/myfile.ext ~/Documents/renamed.ext
请注意,cp
会在不发出警告的情况下覆盖现有文件。
您可以使用do shell script
直接从AppleScript中执行终端命令。
使用上面的AppleScript实现这一点可以这样做:
property y : POSIX file "/Users/CK/Desktop/syringet.jpg" as alias
tell application "Finder"
set x to POSIX path of (target of front window as alias)
set newFileName to text returned of (display dialog "Rename" default answer "")
set y to POSIX path of y
end tell
set command to "cp " & quoted form of y & " " & quoted form of ([x, newFileName] as text)
do shell script command
最后请注意,如果您不想在对话框中指定文件的扩展名(因为您不太可能需要更改该文件),您可以使用name extension
属性。对于 Naamloos.txt ,此属性的值为"txt"
。
修改脚本以反映此实现:
set name of (duplicate y to x with replacing) to newFileName & "." & name extension of y
首先是,或者:
...
set [ext, y] to [name extension, POSIX path] of y
end tell
set command to "cp " & quoted form of y & " " & quoted form of ([x, newFileName, ".", ext] as text)