R11G
R11G

Reputation: 1980

How to get only the latest filename inside the directory

My requirement is to ssh to a linux box and then traverse to a directory and get the latest file's name all through Java code.

I am stuck at retrieving the latest file name. Here is what I am using

ls -ltr /abc/dir/sub_dir|tail -n 1|cut -d' ' -f 11

But this does not work all the times. Usually on doing ls -ltr on a directory, the output will be something like the below pattern.

-rw-r--r-- 1 xyz users   2070 May 27 20:16 9ZVU8ZNLL.xml
-rw-r--r-- 1 xyz users   1507 May 28 02:29 VU8ZNLL.xml
-rw-r--r-- 1 xyz users   1507 May 28 13:59 U8ZNLL.xml
-rw-r--r-- 1 xyz users    944 May 28 14:46 Q9ZVU8ZNLL.xml

Using the above utility sometimes I get the file name and sometimes I get the date or timestamp or a null value which causes problem in my further processing. What is the best way to get ONLY the latest file name.

Upvotes: 1

Views: 910

Answers (3)

jaypal singh
jaypal singh

Reputation: 77085

This should work but it will break if your filenames have spaces in them.

ls -ltr | tail -n 1 | awk '{ print $NF }' 

As @EricJablow stated in the comments, you can by-pass -l option and skip awk altogether.

ls -tr | tail -n 1

Upvotes: 1

proko
proko

Reputation: 1210

I have a similar use case: find the newest folder matching a pattern "foo" in a directory. The same thing can easily be adapted to find any file.

Try:

find . -mindepth 1 -maxdepth 1 -name "*" -type f -printf '%f\n' | xargs ls -d --sort=time | head -1

find "." ... directory path
-name "*" ... pattern match
-type f ... only find files, no directories

The result is converted, sorted by time and the newest element is returned.

Upvotes: 0

Eric Jablow
Eric Jablow

Reputation: 7899

Are you running the Java program on the remote machine, or are you running locally and trying to invoke ssh from it? If you want a local program that invokes ssh somehow to run commands on the remote machine, look at the jSch library from JCraft. Here is an example by Ayberk Cansever. You can use the UNIX pipelines other people have given instead of the command in the example.

If you are invoking ssh and trying to run a Java file on the remote machine, I would guess that the point of the assignment isn't to invoke a shell from your Java program, but to use the capabilities of the Java 7 Files object or its predecessors in earlier Java versions. Look at Files.readAttributes(), Files.walkFileTree(), and Files.getLastModifiedTime(). This seems unlikely, because Java buys you nothing in this case.

Upvotes: 0

Related Questions