How to Add Line Numbers to Text Output Using the nl Command in Linux

When you are attempting to debug a 5,000-line Python script that threw an error on line 4217, staring at a raw text file in the Linux terminal is mathematically impossible. The standard cat command simply dumps the text to the screen without any architectural reference points, leaving you completely blind to the structure. To force the Linux kernel to analyze the file and systematically inject a perfectly sequenced integer at the beginning of every single line, you must use the nl command.

Executing a Global Number Injection

The nl (Number Lines) command is a specialized text-processing engine. It reads a file, calculates the absolute mathematical sequence, and outputs a highly structured, numbered report directly to the terminal.

To execute the core numbering sequence on a chaotic script (e.g., script.py), type:

nl script.py

The exact millisecond you press Enter, the engine rips through the code and violently injects a right-justified number array in front of the data. You can now instantly scroll down and isolate the exact location of line 4217.

CRITICAL ARCHITECTURAL RULE: By default, the nl engine is programmed to explicitly ignore blank lines. It will not assign a number to an empty space. This ensures your code line numbers remain mathematically accurate to the actual logical structure of the program.

Forcing an Absolute Number Injection

If you do not want the engine to skip blank lines—for example, if you are numbering a raw data file where the blank spaces represent critical missing variables—you must override the default logic engine by injecting the -b a (body numbering all) flag.

nl -b a script.py

The engine will now mathematically force a sequenced integer onto every single line, regardless of whether it contains text or is completely void.

Customizing the Injection Architecture

The nl command allows for deep customization of the numerical formatting.

If you want to inject a specific text string (like a colon or a dash) directly between the number and the code to make it visually distinct, you can use the -s (separator) flag.

nl -s " :: " script.py

The engine will instantly calculate the sequence and output it as: 1 :: import sys. This allows you to mathematically parse the output with other advanced Linux tools (like awk) by using the specific separator string as a structural anchor.

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.