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.

Syntax

The syntax is:

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

Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin and a trainer for the Linux operating system/Unix shell scripting. He has worked with global clients and in various industries, including IT, education, defense and space research, and the nonprofit sector. Follow him on Twitter, Facebook, Google+.

Leave a Comment