Output file lines from last to first in Bash

后端 未结 5 1547
说谎
说谎 2020-12-13 00:35

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,

相关标签:
5条回答
  • 2020-12-13 00:53

    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

    0 讨论(0)
  • 2020-12-13 01:02

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

    tail -r -n10
    
    0 讨论(0)
  • 2020-12-13 01:07

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

    tail -10 logfile | tac

    0 讨论(0)
  • 2020-12-13 01:10

    This is the perfect methods to print output in reverse order

    tail -n 10 <logfile>  | tac
    
    0 讨论(0)
  • 2020-12-13 01:12

    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.

    0 讨论(0)
提交回复
热议问题