Linux 在 Bash 中从最后到第一个输出文件行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8017456/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 07:02:54  来源:igfitidea点击:

Output file lines from last to first in Bash

linuxbashshelltail

提问by Yarin

I want to display the last 10 lines of my log file, starting with the last line- like a normal log reader. I thought this would be a variation of the tail command, but I can't find this anywhere.

我想显示我的日志文件的最后 10 行,从最后一行开始- 就像一个普通的日志阅读器。我认为这将是 tail 命令的变体,但我在任何地方都找不到。

采纳答案by Yarin

I ended up using tail -r, which worked on my OSX (tacdoesn't)

我最终使用了tail -r,它在我的 OSX 上工作(tac没有)

tail -r -n10

回答by Rick Smith

GNU (Linux)uses the following:

GNU (Linux)使用以下内容

tail -n 10 <logfile> | tac

tail -n 10 <logfile>prints out the last 10 lines of the log file and tac(cat spelled backwards) reverses the order.

tail -n 10 <logfile>打印出日志文件的最后 10 行并tac(cat 向后拼写)颠倒顺序。

BSD (OS X)of tailuses the -roption:

BSD (OS X)tail使用-r选项:

tail -r -n 10 <logfile>

For both cases, you can try the following:

对于这两种情况,您可以尝试以下操作:

if hash tac 2>/dev/null; then tail -n 10 <logfile> | tac; else tail -n 10 -r <logfile>; fi

NOTE:The GNU manual statesthat the BSD -roption "can only reverse files that are at most as large as its buffer, which is typically 32 KiB" and that tacis more reliable. If buffer size is a problem and you cannot use tac, you may want to consider using @ata's answerwhich writes the functionality in bash.

注意:所述的GNU手册指出的是,BSD-r选项“可以是至多一样大其缓冲器,其通常32只KIB反向文件”,并且tac更加可靠。如果缓冲区大小是一个问题并且您不能使用tac,您可能需要考虑使用@ata 的答案,该答案将功能写入 bash。

回答by drysdam

tacdoes what you want. It's the reverse of cat.

tac做你想做的。是反的cat

tail -10 logfile | tac

tail -10 logfile | tac

回答by ata

You can do that with pure bash:

你可以用纯 bash 做到这一点:

#!/bin/bash
readarray file
lines=$(( ${#file[@]} - 1 ))
for (( line=$lines, i=${1:-$lines}; (( line >= 0 && i > 0 )); line--, i-- )); do
    echo -ne "${file[$line]}"
done

./tailtac 10 < somefile

./tailtac -10 < somefile

./tailtac 100000 < somefile

./tailtac < somefile

./tailtac 10 < 某个文件

./tailtac -10 < 某个文件

./tailtac 100000 < 某个文件

./tailtac < 某个文件

回答by Ashish Kumar Laxkar

This is the perfect methods to print output in reverse order

这是以相反顺序打印输出的完美方法

tail -n 10 <logfile>  | tac