Linux / Unix: Display First Line of a File

last updated in Categories , ,

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: nl(1).

Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.

Share this on (or read 0 comments/add one below):