Add line numbers to a text file in Unix
To add line numbers to a file in Unix, use the nl
command. For example, given an input file cherry.txt
,
class='perl-code'> Loveliest of trees, the cherry now Is hung with bloom along the bough, And stands about the woodland ride Wearing white for Eastertide.
the command
class='perl-code'> nl cherry.txt
gives output
class='perl-code'> 1 Loveliest of trees, the cherry now 2 Is hung with bloom along the bough, 3 And stands about the woodland ride 4 Wearing white for Eastertide.
The command
class='perl-code'> nl -n ln cherry.txt
puts the numbers on the left:
class='perl-code'> 1 Loveliest of trees, the cherry now 2 Is hung with bloom along the bough, 3 And stands about the woodland ride 4 Wearing white for Eastertide.
It is also possible to start from a different number. The command
class='perl-code'> nl -v 100 cherry.txt
gives the output
class='perl-code'> 100 Loveliest of trees, the cherry now 101 Is hung with bloom along the bough, 102 And stands about the woodland ride 103 Wearing white for Eastertide.
The separator between the number and the text line can also be altered:
class='perl-code'> nl -s " -> " cherry.txt
gives the output
class='perl-code'> 1 -> Loveliest of trees, the cherry now 2 -> Is hung with bloom along the bough, 3 -> And stands about the woodland ride 4 -> Wearing white for Eastertide.
It is possible to set the width of the numbers using -w <number>
.
class='perl-code'> nl -v 999 -w 3
gives the output
class='perl-code'> 999 Loveliest of trees, the cherry now 000 Is hung with bloom along the bough, 001 And stands about the woodland ride 002 Wearing white for Eastertide.
The numbers wrap around so they never exceed the width.
Copyright © Ben Bullock 2009-2024. All
rights reserved.
For comments, questions, and corrections, please email
Ben Bullock
(benkasminbullock@gmail.com).
/
Privacy /
Disclaimer