通过脚本清理昨天的文件

Nos*_*tep 3 scripts cron

我想运行一个每天早上运行的 cronjob,以将前一天在特定目录中创建的文件移动到使用先前日期标题创建的文件夹中。

例如,Motion 在名为快照的目录中创建一系列 jpg 文件。我想让脚本运行并在快照目录中找到昨天创建的所有文件(包括它创建的 avi 文件),并将它们移动到一个以昨天的日期作为标题的文件夹中。

有没有人试过这个?Motion 是否已经内置了此功能,而我只是没有看到它?

下一步是让它在 7-14 天后自动清除,但这是另一篇文章。

ter*_*don 5

这是通过find. 相关选项是:

   -mtime n
          File's data was last modified n*24 hours ago.  See the  comments
          for -atime to understand how rounding affects the interpretation
          of file modification times.
   -atime n
          File was last accessed n*24 hours ago.  When  find  figures  out
          how  many  24-hour  periods  ago the file was last accessed, any
          fractional part is ignored, so to match -atime +1, a file has to
          have been accessed at least two days ago.
   -exec command ;
          Execute  command;  true  if 0 status is returned.  All following
          arguments to find are taken to be arguments to the command until
          an  argument  consisting of `;' is encountered.  The string `{}'
          is replaced by the current file name being processed  everywhere
          it occurs in the arguments to the command, not just in arguments
          where it is alone, as in some versions of find.  Both  of  these
          constructions might need to be escaped (with a `\') or quoted to
          protect them from expansion by the shell.  
Run Code Online (Sandbox Code Playgroud)

因此,要移动过去 24 小时内在目录中jpg创建的所有文件snapshots,您将运行

find /home/yourusername/snapshots/ -name '*jpg' -mtime +0 -exec mv {} /path/to/dest
Run Code Online (Sandbox Code Playgroud)

{}被发现的每个文件名替换。引号不是必需的,因为find在执行命令之前会优雅地处理奇怪的文件名。该+0手段“的文件的最后修改时间至少1 * 24小时前作为解释atime上面引述的部分。

如果要将这些移动到名称为昨天日期的目录,则必须创建它(使用该-p选项,因此mkdir如果目录存在,则不会抱怨):

mkdir -p $(date -d yesterday +%F)
Run Code Online (Sandbox Code Playgroud)

date命令将以YYYY-MM-DD格式打印昨天的日期。例如,2014-06-18。您可以将这两个命令组合到同一个find -exec调用中(\after-mtime只是为了便于阅读,它允许您将命令分成多行):

find /home/yourusername/snapshots/ -name '*jpg' -mtime +0 \
 -exec bash -c "mkdir -p $(date -d yesterday +%F) && mv {} $(date -d yesterday +%F)" \;
Run Code Online (Sandbox Code Playgroud)

因此,要使用 运行它cron,您可以在crontab(run crontab -e) 中添加这样一行:

0 9 * * * find /home/yourusername/snapshots/ -name '*jpg' -mtime +0 -exec bash -c "mkdir -p $(date -d yesterday +%F) && mv {} $(date -d yesterday +%F)" \;
Run Code Online (Sandbox Code Playgroud)

以上将在find每天上午 9 点运行该命令。