Get First N Lines From File on Linux

Get First N Lines From File on Linux

When working with extensive text files, logs, or data-centric files on Linux systems, it's a common requirement to retrieve the first set of lines for analysis, monitoring, or diagnostic purposes. This is particularly beneficial for system administrators, developers, and analysts who frequently need to extract data from these files. This tutorial explains how to get the first N lines from a file on Linux.

Create a new file for testing:

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

The head command is a standard tool on Linux used to show the first N lines of a file. For example, if you wish to extract the first 4 lines from a file, execute the following command:

head -4 test.txt

Output example:

Line1
Line2
Line3
Line4

Leave a Comment

Cancel reply

Your email address will not be published.