UNIX gurus! what command do i use to...

Discussion in 'OT Technology' started by babygodzilla, May 27, 2007.

  1. babygodzilla

    babygodzilla I love rice

    Joined:
    Nov 5, 2001
    Messages:
    3,108
    Likes Received:
    0
    ... find the last 10 modified files in a directory AND it's subdirectories (recursively).

    i do

    Code:
    ls -Rlt | head -10 
    and it does the job, except it doesn't list the files modified within a subdirectory. rather, it only lists the sub-directory containing the file. For example, if I have a file in /Downloads/Torrents that fits this criteria, and i do an ls -Rlt | head -10 in /Downloads/, then the folder "Torrents" will be part of the output, instead of the file IN /Torrents.

    are there any other commands that can sort by modified time? "find" can sorta do the job, but it needs a specific time like "within 1 day," or "the last 24 hours." and that's a lil too specific for me.

    THANKS!
     
  2. TheDarkHorizon

    TheDarkHorizon \xC0\xFF\xEE

    Joined:
    Sep 26, 2002
    Messages:
    2,396
    Likes Received:
    0
    Location:
    San Francisco, CA
    If you aren't opposed to using a script, here's something in python:

    Code:
    #!/usr/bin/env python
    import os
     
    all = []
    
    for root, dirs, files in os.walk('.'):
        for name in files:
            # Append tuple (rel_file, st_mtime)
            try:
                all.append(('%s/%s' % (root, name), os.stat('%s/%s' % (root, name))[8]))
            except OSError:
                pass
    
    all.sort(key=(lambda x: x[1]), reverse=True)
    
    print '\n'.join([file[0] for file in all][:10])
    
     
  3. babygodzilla

    babygodzilla I love rice

    Joined:
    Nov 5, 2001
    Messages:
    3,108
    Likes Received:
    0
    will that be faster than a PHP script? i am trying to improve an existing PHP script that lists files in a directory and its subdirectories. but its Search function is quite slow because what it does is it looks at each file and subdirectories recursively. so i thought using a UNIX command will be faster.

    edit: got an error

     
  4. TheDarkHorizon

    TheDarkHorizon \xC0\xFF\xEE

    Joined:
    Sep 26, 2002
    Messages:
    2,396
    Likes Received:
    0
    Location:
    San Francisco, CA
    What's the error? It runs fine for me (Python2.5). How fast do you need it to be? Depending on the implementation in PHP, it would probably be about the same. The calls to stat() are expensive. You're not going to get much more speed out of UNIX commands. It didn't take very long when I ran it against my home directory.
     
  5. TheDarkHorizon

    TheDarkHorizon \xC0\xFF\xEE

    Joined:
    Sep 26, 2002
    Messages:
    2,396
    Likes Received:
    0
    Location:
    San Francisco, CA
    Fixed the issue in older versions of Python. Change line 13 to:
    Code:
    all.sort(lambda x,y: cmp(x[1], y[1]))
    all.reverse()
    
     

Share This Page