Get Most Recent File in a Directory on Linux

Get most recent file in a directory on Linux

ls -Art | tail -n 1

Not very elegant, but it works.

Used flags:

-A list all files except . and ..

-r reverse order while sorting

-t sort by time, newest first

How to recursively find the latest modified file in a directory?

find . -type f -printf '%T@ %p\n' \
| sort -n | tail -1 | cut -f2- -d" "

For a huge tree, it might be hard for sort to keep everything in memory.

%T@ gives you the modification time like a unix timestamp, sort -n sorts numerically, tail -1 takes the last line (highest timestamp), cut -f2 -d" " cuts away the first field (the timestamp) from the output.

Edit: Just as -printf is probably GNU-only, ajreals usage of stat -c is too. Although it is possible to do the same on BSD, the options for formatting is different (-f "%m %N" it would seem)

And I missed the part of plural; if you want more then the latest file, just bump up the tail argument.

How can I list (ls) the 5 last modified files in a directory?

Try using head or tail. If you want the 5 most-recently modified files:

ls -1t | head -5

The -1 (that's a one) says one file per line and the head says take the first 5 entries.

If you want the last 5 try

ls -1t | tail -5

How to find the most recent file containing a particular text in Unix?

I tweeked my initial command to get the desired results. I'm posting here for future searches:

find . -type f | xargs grep -l "text to find" | xargs ls -rt | tail -1

How to get the most recent file of a directory in Java

You can loop through files for directory and compare them and find the last modified one.

public File getLastModifiedFile(File directory) {
File[] files = directory.listFiles();
if (files.length == 0) return null;
Arrays.sort(files, new Comparator<File>() {
public int compare(File o1, File o2) {
return new Long(o2.lastModified()).compareTo(o1.lastModified());
}});
return files[0];
}

To get last modified time:

 File file = getLastModifiedTime("C:\abcd");
long lastModified = file != null ? file.lastModified() : -1 // -1 or whatever convention you want to infer no file exists

Find Most Recent File in a Directory That Matches Certain File Size

This should work:

ls -lh --sort=time /path/to/directory/*.file | grep "3.0M" | head -n =1

Get the latest file in directory

Add the -d argument to ls. That way it will always print just what it's told, not look inside directories.

How to get the second latest file in a folder in Linux

To do diff of the last (lately modified) two files:

ls -t | head -n 2 | xargs diff


Related Topics



Leave a reply



Submit