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
Output file lines from last to first in Bash
提问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 (tac
doesn'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 tail
uses the -r
option:
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 -r
option "can only reverse files that are at most as large as its buffer, which is typically 32 KiB" and that tac
is 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
tac
does 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