Linux / Unix: Display First Line of a File

by on January 27, 2013 · 0 comments· LAST UPDATED January 27, 2014

in , ,

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

TwitterFacebookGoogle+PDF versionFound an error/typo on this page? Help us!

{ 0 comments… add one now }

Leave a Comment

Tagged as: , ,

Previous Faq:

Next Faq: