Applescript:重复stations以删除文件(并保留最少数量的文件)

Applescript:重复stations以删除文件(并保留最少数量的文件),applescript,automator,Applescript,Automator,我在一个现有文件夹中有一堆文件,试图使用Automator首先生成一个文件列表,按名称降序排序,然后使用Applescript丢弃最旧的2个文件,以便在该文件夹中总共保留4个文件 下面是我使用的代码: on run {input, parameters} if not (count input) > 4 then return try repeat with i in items -2 thru -1 of input # To mo

我在一个现有文件夹中有一堆文件,试图使用Automator首先生成一个文件列表,按名称降序排序,然后使用Applescript丢弃最旧的2个文件,以便在该文件夹中总共保留4个文件

下面是我使用的代码:

on run {input, parameters}
    if not (count input) > 4 then return
    try
        repeat with i in items -2 thru -1 of input
            # To move to Trash, use Finder.
            tell application "Finder" to delete alias (i as text)
        end repeat
    end try
end run
它工作得很好,但当我在该文件夹中总共有5个文件时会出现问题;该脚本将丢弃最旧的2个文件,最终我将得到总共3个文件。如何设置我的
if
repeat
语句,以便我可以始终维护总共4个文件,并简单地丢弃该文件夹中最旧的额外文件数?

Easy algorithm

  • 数一数文件并减去4
  • 如果结果小于1,则中止脚本
  • 在循环中向后删除文件

运行时{input,parameters}
将numberOfFilesToDelete设置为(计数输入)-4
如果numberOfFilesToDelete<1,则返回
重复从1到numberOfFilesToDelete的i
告诉应用程序“Finder”删除输入的第i项
结束重复
返回输入——如果没有后续操作,则删除此行
终点

假设列表中的最后一个项目是最早的,只需将输入范围更改为
项目5到-1
。为什么
返回输入?在这方面没有必要这样做case@user3439894这是自动装置的一个常见习惯,它会将某些东西传递给下一个动作。我很清楚这一点,但你没有抓住要点。这是不必要的代码,不应该存在。在运行Apple脚本操作之后,他的工作流中没有其他操作。即使有,传递输入也有什么作用,因为某些输入已被删除。@user3439894您如何知道没有后续操作?并且文件已被移动到垃圾箱文件夹。我知道,因为我在另一个问题中看到了他的工作流程。此外,他没有在他张贴的代码,因此他不需要它。
on run {input, parameters}
    set numberOfFilesToDelete to (count input) - 4
    if numberOfFilesToDelete < 1 then return
    repeat with i from 1 to numberOfFilesToDelete
        tell application "Finder" to delete item -i of input
    end repeat
    return input -- Delete this line if there is no subsequent action
end run