nl
nl
The nl
command in Unix and Linux is used to number lines in a file or standard input. It's particularly useful for adding line numbers to text files or when processing data that requires line-by-line numbering.
Basic Usage
The basic syntax for the nl
command is:
options
: Command-line options to control the behavior ofnl
.file
: The file to be processed. If no file is specified,nl
reads from standard input.
Examples
Numbering Lines in a File
To number lines in a file:
This command outputs each line of file.txt
preceded by its line number.
Example output:
Displaying Line Numbers Only
To display only line numbers without the content of each line:
Example output:
Customizing Line Number Formatting
To customize the format of line numbers, use the -n
option followed by a format specifier:
ln
- Left justified, no leading zeros.rn
- Right justified, no leading zeros.rz
- Right justified, leading zeros.
For example, to right-justify line numbers with leading zeros:
Example output:
Adding Headers
To add a header to each page of output:
This command adds line numbers only to non-empty lines and separates them from the content with a period and space.
Example output:
Options
-b
Option: Body Selection
a
- Number all lines.t
- Number only non-empty lines.n
- Do not number lines.
-s
Option: Separator
Specifies the string to use as a separator between the line number and the line contents.
-w
Option: Line Width
Specifies the number of columns to use for the line number. Useful for adjusting spacing.
-v
Option: Starting Line Number
Specifies the starting line number. By default, it starts at 1.
Practical Use Cases
Numbering Code Files
When reviewing code or scripts, numbering lines helps reference specific lines for discussion or debugging.
Adding Line Numbers to Reports
When generating reports or documents, nl
can be used to add line numbers for easier navigation and referencing.
Formatting Data Files
When working with data files that lack structure, nl
can add structure by numbering each line, making it easier to process and analyze.
Summary
The nl
command is a straightforward yet powerful utility for numbering lines in text files or data streams. It provides several options for customizing line numbering formats, handling empty lines, and adding headers, making it versatile for various text processing tasks. Understanding these options can significantly enhance your ability to manipulate and analyze textual data efficiently.
help
Last updated