Shell – How to find the newest file in a directory that contains a certain string

filesfindgrepshell

I have a need to search a certain folder for the newest created file and grep the contents for a pattern. I have had ok success so far using this command:

find /var/log/folder -type f -printf '%T+ %p\n' | sort | tail -n1 | xargs grep 'string to find'

This does find the latest file that has the match but I am getting an unexpected line in stdout.

$ 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

How can I change my command so it does not give me the "no such file or directory" line?

Best Answer

ls -1rt /path/to/files/ | tail -n1 will find the newest file in a directory (in terms of modification time); pass that as an argument to grep:

grep 'string to find' "$(ls -1rt /path/to/files/ | tail -n1)"
Related Question