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

by on February 28, 2014 · 0 comments· LAST UPDATED February 28, 2014

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
TwitterFacebookGoogle+Found an error/typo on this page? Help us!

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

{ 0 comments… add one now }

Leave a Comment

Tagged as: