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:
Here is a Bash script version that is easier to read: