如何通过终端获取最新文件的名称? [英] How do I get the name of the newest file via the Terminal?

查看:128
本文介绍了如何通过终端获取最新文件的名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试为OS X创建用于 Keyboard Maestro 的宏,执行以下操作:

I'm trying to create a macro for Keyboard Maestro for OS X doing the following:


  1. 根据创建的日期获取磁盘目录中最新文件的名称;

  2. 粘贴文本最新文件:加上最新文件的名称。

其中一个选项是执行shell脚本 ,所以我认为这将为1.在Googling一点后我想出了:

One of its options is to "Execute a shell script", so I thought that would do it for 1. After Googling around a bit I came up with this:

cd /path/to/directory/
ls -t | head -n1

这会将其排序,并返回第一个文件名。然而,它似乎也包括一个换行,我不想要。至于2:我可以输出文本最新文件:与应用程序中的不同的操作,并粘贴文件名后面。但我想知道你是否不能返回随机文本+ ls 命令的结果。

This sorts it right, and returns the first filename. However, it also seems to includes a line break, which I do not want. As for 2: I can output the text "newest file: " with a different action in the app, and paste the filename behind that. But I'm wondering if you can't return "random text" + the outcome of the ls command.

所以我的问题是:我可以只使用 ls 命令吗?

So my question is: can I do this only using the ls command? And how do I get just the name of the latest file without any linebreaks or returns?

推荐答案

如何获得最新文件的名称,因为你已经在使用管道,只是抛出另一个:

Since you're already using pipes, just throw another one in there:

ls -t | head -n1 |awk '{printf("newest file: %s",$0)}'

(请注意,printf在结尾处不包含\\\
;这样可以避免换行)

(Note that the "printf" does not include a '\n' at the end; that gets rid of the linebreak)

编辑:

由于Arkku的建议,在第一行后退出awk,它看起来像:

With Arkku's suggestion to exit awk after the first line, it looks like:

ls -t | awk '{printf("newest file: %s",$0);exit}'

这篇关于如何通过终端获取最新文件的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆