简体   繁体   中英

Output file lines from last to first in Bash

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.

GNU (Linux) uses the following :

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.

BSD (OS X) of tail uses the -r option:

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 states that 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 answer which writes the functionality in bash.

tac does what you want. It's the reverse of cat .

tail -10 logfile | tac

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

tail -r -n10

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

tail -n 10 <logfile>  | tac

You can do that with pure 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM