![](/img/trans.png)
[英]How to delete first two lines and last four lines from a text file with bash?
[英]Output file lines from last to first in Bash
我想显示我的日志文件的最后10行, 从最后一行开始 - 就像普通的日志阅读器一样。 我认为这将是tail命令的变体,但我无法在任何地方找到它。
GNU(Linux) 使用以下内容 :
tail -n 10 <logfile> | tac
tail -n 10 <logfile>
打印出日志文件的最后10行, tac
(cat拼写向后)反转顺序。
tail
BSD(OS X)使用-r
选项:
tail -r -n 10 <logfile>
对于这两种情况 ,您可以尝试以下方法:
if hash tac 2>/dev/null; then tail -n 10 <logfile> | tac; else tail -n 10 -r <logfile>; fi
注意: GNU手册指出 BSD -r
选项“只能反转最多与其缓冲区一样大的文件,通常为32 KiB”,并且tac
更可靠。 如果缓冲区大小有问题并且您无法使用tac
,您可能需要考虑使用@ ata的答案 ,该答案将功能写入bash。
tac
做你想要的。 这是cat
的逆转。
tail -10 logfile | tac
我最终使用tail -r
,它在我的OSX上工作( tac
没有)
tail -r -n10
这是以相反顺序打印输出的完美方法
tail -n 10 <logfile> | tac
你可以用纯粹的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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.