如何在包含某个字符串的目录中找到最新的文件?

use*_*029 5 shell grep find files

我需要在某个文件夹中搜索最新创建的文件并 grep 模式的内容。到目前为止,我已经使用此命令取得了成功:

find /var/log/folder -type f -printf '%T+ %p\n' | sort | tail -n1 | xargs grep 'string to find'
Run Code Online (Sandbox Code Playgroud)

这确实找到了具有匹配项的最新文件,但我在标准输出中得到了意外的一行。

$ find /var/log/folder -type f -printf '%T+ %p\n' |   sort | tail -n1 | xargs grep 'string to find'
grep: 2016-05-12+20:01:59.0570667340: No such file or directory
/var/log/folder/file:string to find
Run Code Online (Sandbox Code Playgroud)

如何更改我的命令,使其不给我“没有这样的文件或目录”行?

Dop*_*oti 6

ls -1rt /path/to/files/ | tail -n1将在目录中找到最新的文件(就修改时间而言);将其作为参数传递给grep

grep 'string to find' "$(ls -1rt /path/to/files/ | tail -n1)"
Run Code Online (Sandbox Code Playgroud)