How To Number Lines In Linux File

When working with Linux files, you often need to number the lines for tracking or debugging purposes. This tutorial will walk you through a simple process of numbering lines in a Linux file and formatting the output as HTML. The tool we will use is called nl, one of the hidden gems of the Linux command line. Let’s get started!

Numbering Lines in a Linux File Using nl

The nl command is used to number the lines of files. The basic syntax for this command is as follows:

nl [options] [file]

Let’s consider a simple example to illustrate its use. Suppose we have a file named “example.txt” and we want to number its lines. The command will look like this:

        nl example.txt

This will output each line of “example.txt”, preceded with the line number.

Formatting Output as HTML

Once you’ve numbered the lines in your Linux file, you may want to format the output as HTML. This can be achieved by writing a bash script that uses the nl command and wraps its output in the appropriate HTML tags. Here’s a basic script that accomplishes this:

        echo ""
        echo ""
        echo "<pre>"
        nl $1 | while read line
            echo "${line}"
        echo "</pre>"
        echo ""
        echo ""

You can run this script with your filename as the argument:

        ./ example.txt

This will output an HTML file with the contents of “example.txt”, each line numbered and properly formatted according to HTML standards.


Numbering lines in Linux files is a highly useful technique that can enhance your productivity and efficiency when working with files. Coupled with HTML formatting, it provides a clear and structured way of presenting file content. The beauty of Linux lies in its vast array of versatile commands like nl, each offering unique functionality to tackle a wide range of tasks.