To add line numbers to a file in Unix, use the nl
command. For example, given an input file cherry.txt,
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
nl cherry.txtgives output
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
nl -n ln cherry.txtputs the numbers on the left:
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
nl -v 100 cherry.txtgives the output
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:
nl -s " -> " cherry.txtgives the output
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>.
nl -v 999 -w 3gives the output
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.