Languages and Scripting
Showing results for 
Search instead for 
Do you mean 

sh script - grep files for string and only use latest file

SOLVED
Go to Solution
Super Advisor

sh script - grep files for string and only use latest file

I need to be able to search a directory for a string.

But, if there are multiple files that contain that string, only use the latest file.

 

I thought I had it, but it does not seem to work.

file=`grep -l ${tn} *| tail -1`

 

I tried head too, but that does not work either...

 

This is an HPUX server with #!/bin/sh

 

4 REPLIES
Honored Contributor

Re: sh script - grep files for string and only use latest file

Try this:

 

file=$(grep -l ${tn} * | xargs ls -1tr | tail -1)

 The 'xargs ls -1tr' (yes, that is the number one, NOT a lower-case L) will sort the files by last modification time in reverse order (newest last) and only print the file name on the line.

 

# man ls 

 

for more details.

 

Also, it is better to use the $( ) syntax for commands rather than the back-ticks enclosing the commands.  The $( ) is much easier to read.

Honored Contributor

Re: sh script - grep files for string and only use latest file

You could also do:

 

file=$(grep -l ${tn} * | xargs ls -1t | head -1)

 This will sort the files by last modification time with the newest FIRST in the list and the head -1 will give you the first file.

Acclaimed Contributor

Re: sh script - grep files for string and only use latest file

>The 'xargs ls -1tr' (yes, that is the number one

 

No real need to use -1 if you are sending the output of ls(1) to pipe or a file.

 

If you know you don't have zillions of files you can get away with:  :-)

file=$(ls -t $(grep -l ${tn} *) | head -1)

 

Above is where you need to use $() vs ``, since nested.

Highlighted
Super Advisor

Re: sh script - grep files for string and only use latest file

Thank you! Worked like a charm!