Unix / Linux: Show First 10 or 20 Lines Of a File

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

in , ,

I have a directory with many files. I am trying to write a shell script that will only show first 10 or 20 lines of a file. How do I display first 10 or 20 lines of a file on Linux or Unix-like systems?

You can use any one of the following command on Unix or Linux to view first 10 lines of a file:

  1. head command
  2. Tutorial details
    DifficultyEasy (rss)
    Root privilegesNo
    RequirementsNone
    Estimated completion time1m
  3. sed command
  4. awk command
  5. Perl/Python/Php/Ruby

head command example to print first 10/20 lines

Type the following head command to display first 10 lines of a file named "bar.txt":

head -10 bar.txt

Type the following head command to display first 20 lines of a file named "bar.txt":

head -20 bar.txt

sed command example to print first 10/20 lines

Type the following sed command to display first 10 lines of a file named "/etc/group":

sed -n 1,10p /etc/group

Type the following sed command to display first 20 lines of a file named "/etc/group":

sed -n 1,20p /etc/group

awk command example to print first 10/20 lines

Type the following awk command to display first 10 lines of a file named "/etc/passwd":

awk 'FNR <= 10' /etc/passwd

Type the following awk command to display first 20 lines of a file named "/etc/passwd":

awk 'FNR <= 20' /etc/passwd

perl command example to view first 10/20 lines of a file

Type the following perl command to display first 10 lines of a file named "/etc/passwd":

perl -ne'1..10 and print' /etc/passwd

Type the following perl command to display first 20 lines of a file named "/etc/passwd":

perl -ne'1..20 and print' /etc/passwd

Sample outputs from sed, awk, head, and perl commands:

root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
sync:x:5:0:sync:/sbin:/bin/sync
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
halt:x:7:0:halt:/sbin:/sbin/halt
mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
uucp:x:10:14:uucp:/var/spool/uucp:/sbin/nologin

I strongly suggest that you read man pages - head(1), sed(1), perl(1), awk(1) for more information.

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: