Linux ls 命令的前两个结果
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10520120/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
first two results from ls command
提问by Fidel
I am using ls -l -t
to get a list of files in a directory ordered by time.
我ls -l -t
用来获取按时间排序的目录中的文件列表。
I would like to limit the search result to the top 2 files in the list.
Is this possible?
I've tried with grep and I struggled.
我想将搜索结果限制为列表中的前 2 个文件。
这可能吗?
我已经尝试过 grep 并且我很挣扎。
采纳答案by dag
You can pipe it into head
:
您可以通过管道将其导入head
:
ls -l -t | head -3
Will give you top 3 lines (2 files and the total).
会给你前 3 行(2 个文件和总数)。
This will just give you the first 2 lines of files, skipping the size line:
这只会给你前两行文件,跳过大小行:
ls -l -t | tail -n +2 | head -2
tail
strips the first line, then head
outputs the next 2 lines.
tail
剥离第一行,然后head
输出接下来的 2 行。
回答by larsks
You can use the head
command to grab only the first two lines of output:
您可以使用该head
命令仅获取输出的前两行:
ls -l -t | head -2
回答by Pier-Alexandre Bouchard
You have to pipe through head.
你必须通过头管。
ls -l -t | head -n 3
ls -l -t | 头-n 3
will output the two first results.
将输出前两个结果。
回答by Stephen P
To avoid dealing with the top output line you can reverse the sort and get the last two lines
为避免处理顶部输出行,您可以反转排序并获取最后两行
ls -ltr | tail -2
This is pretty safe, but depending what you'll do with those two file entries after you find them, you should read Parsing lson the problems with using ls
to get files and file information.
这是非常安全的,但是取决于您在找到这两个文件条目后将如何处理它们,您应该阅读解析 lsls
以了解使用获取文件和文件信息的问题。
回答by Saad Rehman Shah
Or you could try just this
或者你可以试试这个
ls -1 -t | head -2
The -1 switch skips the title line.
-1 开关跳过标题行。