Simpler Navigation for Servers and Operating Systems - Please Update Your Bookmarks
Completed: a much simpler Servers and Operating Systems section of the Community. We combined many of the older boards, so you won't have to click through so many levels to get at the information you need. Check the consolidated boards here as many sub-forums are now single boards.
If you have bookmarked forums or discussion boards in Servers and Operating Systems, we suggest you check and update them as needed.
Languages and Scripting
cancel
Showing results for 
Search instead for 
Did you mean: 

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

SOLVED
Go to solution
Ratzie
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
Patrick Wallek
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.

Patrick Wallek
Honored Contributor
Solution

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.

Dennis Handly
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
Ratzie
Super Advisor

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

Thank you! Worked like a charm!