≡ Menu

Linux/Unix: Bash/KSH SHELL Print nth Line Of a Text File

Fig.01: Linux/Unix: Bash/KSH SHELL Print nth Line Of a Text File

You can display or print the n’th line of a file using any one of the following command on Bash/KSH/TCSH/CSH or SH based shell running on Linux/Unix-like systems:

Print 5th line using sed

sed -n "5p" filename

To print 10-20 lines, type:

sed -n "10,20p" filename

To display line numbers:

sed -n "10,20p" filename | cat -n

OR

sed -n "10,20p" filename | less -N

Print 10th line using head command

head -n "10" filename | tail -n 10

Print 42nd line using awk command

awk "NR==42{print;exit}" filename

OR print 13 to 42 lines:

awk "NR>=13{print} NR==42{exit}" /etc/passwd

Print 1 to 5 lines and number it on screen:

awk "NR>=1{print} NR==5{exit}" /etc/group | cat -n

Sample outputs:

     1	root:x:0:root
     2	bin:x:1:root,bin,daemon
     3	daemon:x:2:root,bin,daemon
     4	sys:x:3:root,bin,adm
     5	adm:x:4:root,adm,daemon
Share this tutorial on:

Examples and usage: Linux: Display First Ten Lines (1-10) With Numbers Command

{ 4 comments… add one }
  • pradeep September 3, 2015, 2:47 pm

    Print 10th line using head command — is not working

    • Suraj Branwal March 7, 2016, 3:34 pm

      you can use below to print 10th line from file.

      head -10 $file | tail -1

      Cheers,
      Suraj

  • santh April 6, 2016, 9:54 am

    good post

  • ranjeet kr June 23, 2016, 2:04 pm

    how to print 5th line of /etc/passwd.
    how to print 5th line of only /var/spool/lpd in /etc/passwd
    how to print only 5th line of “lpd” in /etc /passwd

Leave a Comment


   Tagged with: