Linux nl Command: Line Numbering

LinuxLinuxBeginner
Practice Now

Introduction

This tutorial provides an overview of the nl command in Linux, focusing on its functionality for numbering lines in text files.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL linux(("`Linux`")) -.-> linux/BasicSystemCommandsGroup(["`Basic System Commands`"]) linux/BasicSystemCommandsGroup -.-> linux/nl("`Line Numbering`") subgraph Lab Skills linux/nl -.-> lab-210988{{"`Linux nl Command: Line Numbering`"}} end

nl Command

The nl command is used to number lines in a text file. It is particularly useful when you want to reference specific lines in a document.

Command Usage

Let's start with a basic example of using the nl command. We have a file called example.txt in the /home/labex/project directory. Consider the following command and its output:

terminal

Input:

nl /home/labex/project/example.txt

Output:

     1  Hello Labex!
     2  This is a sample text.

     3  Have a nice day.

In this example, the example.txt file is processed by nl, and the output displays the file's content with line numbers.

Parameters and Usage Examples

To fully grasp the functionality of the nl command, let's categorize and explore its various parameters.

Option Parameter

nl [OPTION] file

  • -b a: Specifies that the line number will be listed, regardless of whether it is a blank line or not (similar to cat -n).
  • -n rz: The line number is displayed on the far right of its own field, left padded with '0's.

Example Usage

1. Numbered Lines with Text Lines Only (nl -b a)

Specifies that the line number will be listed, regardless of whether it is a blank line or not (similar to cat -n).

Input:

nl -b a /home/labex/project/example.txt

Output:

     1  Hello Labex!
     2  This is a sample text.
     3
     4  Have a nice day.

2. Numbered Lines with Right Zero Padding (nl -n rz)

The line number is displayed on the far right of its own field, left padded with '0's.

Input:

nl -n rz /home/labex/project/example.txt

Output:

000001	Hello Labex!
000002	This is a sample text.

000003	Have a nice day.

In the examples above, nl -b a numbers only non-empty lines, and nl -n rz right-zero-pads the line numbers.

Summary

In this tutorial, we explored the nl command, focusing on its ability to number lines in text files. We introduced basic usage, common parameters, and provided examples to demonstrate the versatility of the nl command. Understanding these features enables users to efficiently annotate and reference lines in their text documents.

Other Linux Tutorials you may like