Grep command to search for a pattern in multiple files and list the files ordering by date

shell

I have a requirement to search for a pattern in multiple files and get the latest file for further processing. I am trying to do this in a shell script. I was trying to do it as follows

file=`grep -lh <pattern> <file_name> | tail -1`

But grep is listing the files as in a ls and not as in ls -lrt. I have tried the following command

ls -lrt `grep -l <pattern> <file name>`

But I'm not able to incorporate this command in the shell script.
Any help is appreciated.

Thanks

Best Answer

This is much faster. Whereas the other answers grep all the files, this searches the newest ones first and stops as soon as it finds the pattern.

This one-liner captures the result in a variable:

file=$(while read file; do grep pattern "$file" >/dev/null;[[ $? ]]; then echo "$file"; break; fi; done < <(find $startdir -maxdepth 1 -type f -printf "%T@:%p\n"|sort -nr|cut -d: -f2-))

Here is a Bash script version that is easier to read:

#!/bin/bash
while read file
do
    grep pattern "$file" > /dev/null
    if [[ $? ]]
    then
        echo "$file"
        break
    fi
done < <(find $startdir -maxdepth 1 -type f -printf "%T@:%p\n" |
            sort -nr |
            cut -d: -f2-)