sh script - grep files for string and only use latest file (361 Views)
Reply
Super Advisor
Ratzie
Posts: 852
Registered: ‎01-10-2002
Message 1 of 5 (361 Views)
Accepted Solution

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

 

Please use plain text.
Honored Contributor
Patrick Wallek
Posts: 13,752
Registered: ‎06-21-2000
Message 2 of 5 (358 Views)

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.

Please use plain text.
Honored Contributor
Patrick Wallek
Posts: 13,752
Registered: ‎06-21-2000
Message 3 of 5 (356 Views)

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.

Please use plain text.
Acclaimed Contributor
Dennis Handly
Posts: 24,971
Registered: ‎03-06-2006
Message 4 of 5 (322 Views)

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.

Please use plain text.
Super Advisor
Ratzie
Posts: 852
Registered: ‎01-10-2002
Message 5 of 5 (315 Views)

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

Thank you! Worked like a charm!
Please use plain text.
The opinions expressed above are the personal opinions of the authors, not of HP. By using this site, you accept the Terms of Use and Rules of Participation