How to tweak linux for Displaying a File with Line Numbers using shell script

Posted on 7:16 PM by Bharathvn

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 as you want to this script, but you can't feed it input via a pipe, though that wouldn't be too hard to fix, if needed.

The Results
$ numberlines text.snippet.txt
1: Perhaps one of the most valuable uses of shell scripts is to fix
2: your particular flavor of Unix and make it more like other flavors,
3: to bring your commands into conformance or to increase consistency
4: across different systems. The outsider view of Unix suggests a
5: nice, uniform command-line experience, helped along by the existence
6: of and compliance with the POSIX standards for Unix. But anyone who's
7: ever touched more than one computer knows how much they can vary
8: within these broad parameters.

Hacking the Script
Once you have a file with numbered lines, you can also reverse the order of all the lines in the file:

cat -n filename | sort -rn | cut -c8-

This does the trick on systems supporting the -n flag to cut, for example. Where might this be useful? One obvious situation is when displaying a log file in most-recent-to-least-recent order.