#31 Displaying a File with Line Numbers

There are a lot of ways to add line numbers to a displayed file, many of which are quite short. Here's a solution using awk:

awk '{ print NR": "$0 }' < inputfile

On some Unix implementations, the cat command has an -n flag, and on others, the more (or less, or pg) pager has a flag for specifying that each line of output should be numbered. But on some Unixes, none of these will work, in which case the simple script given here can do the job.

The Code

#!/bin/sh

# numberlines - A simple alternative to cat -n, etc.

for filename
do
  linecount="1"
  while read line
  do
    echo "${linecount}: $line"
    linecount="$(( $linecount + 1 ))"
  done < $filename
done
exit 0

Running the Script

You can feed as many filenames ...

Get Wicked Cool Shell Scripts now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.