有没有一个命令可以列出我今年修改的所有文件?

Pea*_*er5 4 command-line

我想列出我今年修改过的所有文件并备份它们。有谁知道是否有列出它们的命令?先感谢您。

Hen*_*eck 17

如果要查找文件,该find命令是一个强大的工具。您可以查看目录并打印出与某些测试匹配的所有文件的路径:

# find all files in /some/directory whose name starts with 'project_b'
find /some/directory -iname 'project_b*'

# find all files in /some/directory which are owned by user 'joe'
find /some/directory -user joe

# find all files in /some/directory whose name starts with 'project_b'
# but which are *not* owned by user 'joe'
find /some/directory -iname 'project_b*' -and -not -user joe
Run Code Online (Sandbox Code Playgroud)

要获取文件上次修改的日期(或更准确地说,文件内容的上次​​修改),您可以检查 mtime 时间戳。find有一个 mtime 测试:

# find all files, whose mtime is less than 365 days back
find /some/directory -mtime -365
Run Code Online (Sandbox Code Playgroud)

到目前为止,这为您提供了要备份的所有文件的列表。现在是备份本身。find带来一个名为的选项-exec,该选项将命令应用于它找到的每个文件:

find /some/directory -iname '*.txt' -exec cp {} /somewhere/else \;
Run Code Online (Sandbox Code Playgroud)

如果 find 命令找到test.txt, other.txtand something.txt,则该-exec部分将执行:

cp test.txt /somewhere/else
cp other.txt /somehwere/else
cp something.txt /somewhere/else
Run Code Online (Sandbox Code Playgroud)

您可能会看到,{}被相关文件替换。

编辑:您可能需要找到一个比cp备份本身更好的解决方案,因为cp只会将每个文件复制到/somewhere/else而不保留目录结构。

总体而言,专用备份程序可能是更好的选择。

  • 如果你想维护任何 `find`... um... 找到的目录结构,你可能应该使用类似 `find ... -print0 | 的东西。cpio -p0dv /destination`。`cp` 不维护目录结构(除非源对象是目录)。此外,`cp` 变体可以更好地编写为`-exec cp -t /somewhere/else {} +`,它不会为每个匹配项创建一个新进程。 (4认同)
  • 对于这样的任务,在 `cp` 命令中使用 `--parents` 标志是一个好主意,因为它保留了文件层次结构并备份那些共享相同名称的文件。 (3认同)

小智 5

假设您希望将日期限制在可以-newermt与日期一起使用的当前年份。

这将在当前目录中查找 2016 年 11 月 1 日之后的任何文件,并将它们复制到 /target,同时保持目录结构。

find . -newermt "2016-11-01 00:00:00" -exec cp --parents {} /target \;
Run Code Online (Sandbox Code Playgroud)

--parents加入cp命令可以复制维修器材存在内的文件夹中的文件。

例如...

ubuntu@ubuntu-xenial:~$ ls
percona-release_0.1-4.xenial_all.deb  t  t2  testdir  testfile2.vm  testfile.vm
ubuntu@ubuntu-xenial:~$ cp --parents t/output.txt testdir/
ubuntu@ubuntu-xenial:~$ ls testdir/
directory2  t
Run Code Online (Sandbox Code Playgroud)

当我复制t/output.txttestdir/其创建的文件夹ttestdir/,然后复制该文件。