目录中每个文件的最后 n 行

Last n rows of each files in a directory

假设我有一个目录,里面有 N 个日志文件:

file1.log
file2.log
file3.log
...
fileN.log

我可以使用哪个 linux 命令打印上面每个文件的最后 n 行?

我知道如何打印 1 个文件:

less file1.log | tail -n 5

但我想对目录中的所有 N 个文件同时执行此操作

for 循环不是最好的,因为它不支持所有情况。前任。如果您的文件名中有空格。

为避免所有问题,请使用:

find . -type f -name "*.log" -exec tail -5 {} \; -print
  • .:是当前目录。如果您的日志文件不在当前目录中,您可以将 . 替换为包含文件的目录。
  • 可以修改
  • -name "*.log" 以更精确地过滤您的文件。前任。文件*.log.
  • tail -5 {} 将打印最后 5 行。根据需要更改号码。
  • -print 选项将打印找到的日志的文件名。但如果您不需要在显示中显示该信息,则可以省略它。

使用命令“ls *.log | sort -V | tail -n {number}”,其中number是从末尾输出的文件数。
例如,“ls *.log | sort -V | tail -n 5”将输出到一个只有十个日志文件的目录:
file6.log
file7.log
file8.log
file9.log
file10.log

中间没有插入"sort -V"就不是自然排序,而是机器排序,即"ls *.log | tail -n 10"会输出: file10.log
file1.log
file2.log
file3.log
file4.log
file5.log
file6.log
file7.log
file8.log
file9.log