Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 906
Yarin Avatar asked Nov 05 '11 01:11

Yarin


People also ask

How do I print the first and last line in Linux?

The -s option replicates this without amending each file but streams the results to stdout as if each file is treated separately. Show activity on this post. 1p will print the first line and $p will print the last line. As a suggestion, take a look at info sed, not only man sed .

How do I print the first 5 lines of a file in Linux?

To look at the first few lines of a file, type head filename, where filename is the name of the file you want to look at, and then press <Enter>. By default, head shows you the first 10 lines of a file. You can change this by typing head -number filename, where number is the number of lines you want to see.

How do I print the last 10 lines of a file in Linux?

tail [OPTION]... [ Tail is a command which prints the last few number of lines (10 lines by default) of a certain file, then terminates. Example 1: By default “tail” prints the last 10 lines of a file, then exits.

How do I see the last 20 lines of a file in Linux?

To display last 20 lines of a file linux use the tail command. Displays the last 20 lines. The default is 10 if you leave out the -n option. Displays the last 100 bytes of the file ( without reguard for the lines).


1 Answers

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.

like image 142
Rick Smith Avatar answered Oct 09 '22 15:10

Rick Smith