我有一个文件名格式为 $date.txt 的目录。我想从中提取 5 个最新文件。有没有比这更优雅的解决方案
for f in 2*.txt; do echo $f; done | tail -5 | while read f; do cat $f; done
Run Code Online (Sandbox Code Playgroud)
在ksh93,bash或zsh:
files=( 2*.txt )
cat "${files[@]: -5}"
Run Code Online (Sandbox Code Playgroud)
这将创建一个与模式匹配的文件名数组2*.txt。然后它将输出其中最后五个的内容。
在 中zsh,您还可以指定一系列文件作为其glob 限定符的一部分:
cat 2*.txt([-5,-1])
Run Code Online (Sandbox Code Playgroud)
在任何 POSIX shell 中,这也可以通过
set -- 2*.txt
while [ "$#" -gt 5 ]; do shift; done # or: [ "$#" -gt 5 ] && shift "$(( $# - 5 ))"
cat "$@"
Run Code Online (Sandbox Code Playgroud)
这将位置参数设置为与模式匹配的文件名。然后它从列表的开头移出名称,直到列表中只有五个元素。 cat然后在剩余的文件名上调用。
在所有这些解决方案中,文件将按字典顺序排序。正确处理带有空格或换行符的文件名。