This discussion is archived
2 Replies Latest reply: Jan 13, 2013 8:18 PM by m_malinowski RSS

command to copy last file generated in a directory

dba-hyd Pro
Currently Being Moderated
Please can someone help me with the Linux command to find the last file generated in a directory and copy that file to another location.

I am using Oracle Linux 5.3 OS.
  • 1. Re: command to copy last file generated in a directory
    Dude! Guru
    Currently Being Moderated
    It depends how you determine the last file generated. It could by modification date or based on the file name.

    The following example demonstrates finding the last file by modification date:
    $ mkdir testfiles
    $ cd testfiles
    $ touch 1
    $ touch 2
    $ touch 5
    $ touch 4
    $ touch 3
    
    $ ls -l
    total 0
    -rw-r--r--  1 bb  staff  0 Jan 13 09:50 1
    -rw-r--r--  1 bb  staff  0 Jan 13 09:50 2
    -rw-r--r--  1 bb  staff  0 Jan 13 09:50 3
    -rw-r--r--  1 bb  staff  0 Jan 13 09:50 4
    -rw-r--r--  1 bb  staff  0 Jan 13 09:50 5
    
    $ ls -lt | head -2 | tail -1 | awk '{print $NF}'
    3
    
    $ cp $(ls -lt | head -2 | tail -1 | awk '{print $NF}') ../
    And btw:

    <pre>
    Handle:      DatabaseAdministrator
    Status Level:      Pro (555)
    Registered:      Jul 2, 2007
    Total Posts:      1,468
    Total Questions:      151 (123 unresolved)
    </pre>

    That's many questions unanswered. Please mind the forum etiquette. Thanks.
  • 2. Re: command to copy last file generated in a directory
    m_malinowski Newbie
    Currently Being Moderated
    I would add -a (just in case you have hidden files) and grep -v / (to exclude directory's as you said files) ls -at | grep -v /
    So full command:
    cp $(ls -at | grep -v / |head -1) <path>

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points