≡ Menu

Linux / Unix: Display First Line of a File

How do I display first line of a text file called foo.txt on Linux or Unix-like operating systems?

You display first lines of a file using head command.

Syntax

The syntax is:

Tutorial details
DifficultyEasy (rss)
Root privilegesNo
RequirementsNone
Estimated completion time1m

head filename

OR

head -1 filename

Example: Displaying the first line

Open the Terminal application and type the following command:
$ head -1 foo.txt
The following example will show first 3 lines from /etc/passwd file:
$ head -3 /etc/passwd
Sample outputs:

root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin

To print first 3 lines and number lines of files use nl command as follows:
$ head -3 /etc/passwd | nl
Sample outputs:

     1	root:x:0:0:root:/root:/bin/bash
     2	bin:x:1:1:bin:/bin:/sbin/nologin
     3	daemon:x:2:2:daemon:/sbin:/sbin/nologin

A note about sed command

You can use sed command as follows:
$ sed -n 1p foo.txt

For more information see man pages: sed(1), head(1), nl(1).

Tweet itFacebook itGoogle+ itPDF itFound an error/typo on this page?

{ 0 comments… add one }

Leave a Comment