Get Last N Lines From File on Linux

Get Last N Lines From File on Linux

In the Linux systems, when dealing with large text files, logs, or data-centric files, it's a frequent requirement to access the most recent or last set of lines for analysis, monitoring, or diagnostic purposes. This is especially useful for system administrators, developers, and analysts who regularly extract data from these files. This tutorial shows how to get last N lines from a file on Linux.

For testing purpose, create a new file:

printf "Line1\nLine2\nLine3\nLine4\nLine5\nLine6\nLine7\n" > test.txt

The tail command is a standard utility on Linux used to display the last N lines of a file. Here's how to use it to obtain the last 4 lines from a file:

tail -4 test.txt

Output example:

Line4
Line5
Line6
Line7

Leave a Comment

Cancel reply

Your email address will not be published.