Need ruby code to get a latest file from a Directory

Discussion in 'Ruby' started by Rajeswar reddy Gaulla, Aug 18, 2008.

  1. Hi All,

    I am having log files with time stamp in a log directory, how to open a
    latest log file and read it?.

    Eg:
    directory name log/
    files
    log/log20080812152634Lbuild.34.xml
    log/log20080812122634Lbuild.34.xml
    log/log20080812102634Lbuild.34.xml
    log/log20080811142634Lbuild.34.xml
    log/log20080811122634Lbuild.34.xml

    If anybody know the solution, please let me know.

    With Regards
    GRR
    --
    Posted via http://www.ruby-forum.com/.
     
    Rajeswar reddy Gaulla, Aug 18, 2008
    #1
    1. Advertising

  2. On Tue, Aug 19, 2008 at 02:23:07AM +0900, Rajeswar reddy Gaulla wrote:
    > I am having log files with time stamp in a log directory, how to open a
    > latest log file and read it?.


    Dir.entries('.').sort_by {|f| File.mtime(f)}.reverse[0]

    Does that do what you want?

    --
    nathan
    nathan_at_nathanpowell_dot_org

    If all else fails, immortality can always be assured by spectacular error.
    ~ John Kenneth Galbraith
    ------------------------------------
     
    Nathan Powell, Aug 18, 2008
    #2
    1. Advertising

  3. Rajeswar reddy Gaulla

    Guest

    On Mon, Aug 18, 2008 at 1:23 PM, Rajeswar reddy Gaulla
    <> wrote:
    > I am having log files with time stamp in a log directory, how to open a
    > latest log file and read it?.
    >
    > Eg:
    > directory name log/
    > files
    > log/log20080812152634Lbuild.34.xml
    > log/log20080812122634Lbuild.34.xml
    > log/log20080812102634Lbuild.34.xml
    > log/log20080811142634Lbuild.34.xml
    > log/log20080811122634Lbuild.34.xml
    >
    > If anybody know the solution, please let me know.


    Maybe something like:

    newest_file = Dir.entries(Dir::pwd).sort_by{|e|
    # assuming that the files are always log + TIMESTAMP + L:
    scan(/log\d{14}L/)[0]
    }.last

    File.open(newest_file, "r") do |f|
    #...
    end

    ?
     
    , Aug 18, 2008
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Replies:
    4
    Views:
    6,965
    Roland de Ruiter
    Jul 19, 2006
  2. Hank
    Replies:
    3
    Views:
    410
    Tim Golden
    Oct 30, 2003
  3. Replies:
    1
    Views:
    135
    Bob Barrows [MVP]
    Jun 24, 2005
  4. Mmcolli00 Mom
    Replies:
    2
    Views:
    146
    William James
    Feb 10, 2009
  5. Fily Salas
    Replies:
    8
    Views:
    137
    Fily Salas
    Mar 27, 2011
Loading...

Share This Page