views:

28

answers:

2

I have a directory of files like so:

parent
    /dir1
        file1
        file2
        other
        something
        name_pattern.o23409284
        name_pattern.o29203429
        name_pattern.o39208235
    /dir2
    ...

I want to run a command that will look in the newest name_pattern.o* file for a line beginning with:

***END

So it seems easy enough to do

grep -c '***END' name_pattern.o*

but I want to only look at the most recent file and ignore all others. So I think I need some kind of find command that will choose the newest file. I just don't know how to do that.

+2  A: 
perl -e 'print( ( sort { -M $a <=> -M $b } @ARGV )[0], "\n");' name_pattern.o*

This sorts them by last-modification-time. Swap the $a and $b to have it give oldest instead. There are also modification flags to "find" but I find it difficult to have find do comparative-within-a-directory operations...

If you need it in one-line:

grep '***END' `perl -e 'print( ( sort { -M $a <=> -M $b } @ARGV )[0], "\n");' name_pattern.o*`
eruciform
with so many things in one line, i'd really break it up and do some error checking (i.e. are there 0 files), but theoretically, yes
eruciform
Sorry I deleted that comment because the formatting was all weird. Basically, I want to just put that grep in an if statement to see if it found that line. But I could just store the value in a variable and check that. Thanks!
Matt
awesome, no problem. feel free to green checkmark. ;-)
eruciform
+1  A: 

Even the following can also do it.

ls -t | head -n1 name_pattern.o*

this will select the files that start with the given pattern, latest timestamp comes first, and take only the first file. So finally do this,

grep -c '***END' `ls -t | head -n1 name_pattern.o*`
thegeek
cool, thanks for that one too!
Matt