When you are debugging a massive, unformatted Python script or reviewing a dense configuration file in the Linux terminal using the cat command, pinpointing the exact location of a syntax error is incredibly difficult. If the system throws an error on “Line 142,” you have no way to visually identify which line that actually is. To solve this, you can use the nl (Number Lines) command to automatically append sequential numbering to the left margin of any text output.
How to Use the nl Command
The nl command functions very similarly to cat, but it adds a numbered index to the beginning of every non-blank line in the file.
- Open your Linux terminal.
- Suppose you have a script named
database_script.py. Type the following command:
nl database_script.py
Press Enter. The terminal will output the entire contents of the file, perfectly structured with numbers running down the left side:
1 import os 2 import sys 3 def connect(): 4 print("Connecting...")
Numbering Blank Lines
By default, the nl command is intelligent enough to skip entirely blank lines. It only increments the counter when it encounters actual text or code. However, if you are strictly debugging and need every single line (blank or not) to be numbered exactly as it is in your IDE, you can force it to number everything using the -b a (body numbering: all) flag.
nl -b a database_script.py
Piping Output to nl
The nl command is also incredibly useful when chained together with other commands. If you are running a complex grep search and want to know exactly how many matching results were found, you can simply pipe the output directly into nl.
grep "Error" /var/log/syslog | nl
This will instantly extract every line containing the word “Error” from the system log, and number them 1, 2, 3, etc., allowing you to easily read the output and instantly see the total count at the bottom.