Linux / Unix: Display First Line of a File

Posted on in Categories , , last updated January 27, 2014

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.


The syntax is:

head filename


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:


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).

Leave a Comment