1

我的要求是 ssh 到一个 linux 机器,然后遍历一个目录并通过 Java 代码获取最新文件的名称。

我一直在检索最新的文件名。这是我正在使用的

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

但这并不总是有效。通常在目录上执行 ls -ltr 时,输出将类似于以下模式。

-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

使用上述实用程序有时我会得到文件名,有时我会得到日期或时间戳或空值,这会导致我的进一步处理出现问题。仅获取最新文件名的最佳方法是什么。

4

3 回答 3

1

这应该可以,但是如果您的文件名中有空格,它将中断。

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

正如@EricJablow在评论中所说,您可以绕过-l选项并完全跳过awk

ls -tr | tail -n 1
于 2013-05-29T03:50:37.660 回答
0

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.

于 2013-05-29T04:20:22.217 回答
0

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.

于 2013-05-29T04:21:34.793 回答