Practical Numbering Techniques
Advanced Line Numbering Strategies
1. Selective Line Numbering
## Number only non-empty lines
nl -b t filename.txt
## Number lines starting from specific line
sed -n '5,$p' filename.txt | nl
graph LR
A[Original File] --> B[Numbering Process]
B --> C[Formatted Numbered Output]
Formatting Option |
Command Example |
Zero-padded numbers |
nl -n rz filename.txt |
Right-aligned numbers |
nl -w 5 filename.txt |
Custom number width |
awk '{printf "%05d: %s\n", NR, $0}' file.txt |
3. Scripting Line Numbering
Bash Script Example
#!/bin/bash
## Line numbering with custom formatting
while IFS= read -r line; do
printf "%03d: %s\n" "$line_num" "$line"
((line_num++))
done < input.txt
4. Combining with Text Processing
Filtering and Numbering
## Number lines matching a pattern
grep 'error' logfile.txt | nl
## Number lines excluding specific content
grep -v '^#' config.txt | nl
graph TD
A[Large File] --> B{Numbering Method}
B --> |cat -n| C[Simple, Memory Intensive]
B --> |awk| D[Flexible, Moderate Performance]
B --> |sed| E[Powerful, Slower for Large Files]
Optimization Techniques
- Use streaming commands for large files
- Leverage awk for complex processing
- Avoid loading entire files into memory
6. Real-world Use Cases
Scenario |
Recommended Technique |
Code Review |
nl with line width formatting |
Log Analysis |
awk with pattern matching |
Configuration Parsing |
sed with selective numbering |
Best Practices
- Choose the right tool for specific requirements
- Consider file size and system resources
- Combine line numbering with other text processing commands
Note: LabEx provides hands-on environments to master these advanced line numbering techniques in Linux.