我想显示日志文件的最后 10 行,从最后一行开始 - 就像普通的日志阅读器一样。我认为这将是 tail 命令的变体,但我在任何地方都找不到它。
GNU (Linux) 使用以下内容:
tail -n 10 <logfile> | tac
tail -n 10 <logfile>
打印出日志文件的最后 10 行,tac
(cat 向后拼写)反转顺序。
BSD (OS X) 的
tail
使用 -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
你可以用纯 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
这是逆序打印输出的完美方法
tail -n 10 <logfile> | tac
纯 bash 解决方案是
_tac_echo() {
IFS=$'\n'
echo "${BASH_ARGV[*]}"
}
_tac () {
local -a lines
readarray -t lines
shopt -s extdebug
_tac_echo "${lines[@]}"
shopt -u extdebug
}
cat <<'EOF' | _tac
1 one line[of] smth
2 two line{of} smth
3 three line(of) smth
4 four line&of smth
EOF
打印
4 four line&of smth
3 three line(of) smth
2 two line{of} smth
1 one line[of] smth