Reading Time: 2minutes
Lets say you have a plainjt text TXT file with sentences and you would like to put quickly line numbering in a Linux bash shell. First thing that might pop up to your mind is to use a loop cat text file and print it line by one together with output of incremental values counted from 0 to the number of lines the file contains. This would work but is useless work. As coreutils package already contains a tool called nl ( /usr/bin/nl ). Here is paste from header of nl manual page;
nl – number lines of files
nl [OPTION]… [FILE]…
Thus to put line numbering to lets say this fortune's bible quotes plain text file;
$ nl bible > bible_quotes_numbered.txt
Here is a small chunk of bible_quotes_numbered.txt;
$ cat bible_quotes_numbered.txt
1 In the beginning God created the heaven and the earth.
2 — Genesis 1:1
4 And the earth was without form, and void; and darkness was upon
5 the face of the deep. And the Spirit of God moved upon the face of
6 the waters.
7 — Genesis 1:2
9 And God said, Let there be light: and there was light.
10 — Genesis 1:3
12 And God saw the light, that it was good: and God divided the light
13 from the darkness.
14 — Genesis 1:4
16 And God called the light Day, and the darkness he called Night.
17 And the evening and the morning were the first day.
18 — Genesis 1:5
20 And God said, Let there be a firmament in the midst of the waters,
21 and let it divide the waters from the waters.
22 — Genesis 1:6
24 And God made the firmament, and divided the waters which were under
25 the firmament from the waters which were above the firmament: and
26 it was so.
27 — Genesis 1:7
29 And God called the firmament Heaven. And the evening and the morning
30 were the second day.
31 — Genesis 1:8
33 And God said, Let the waters under the heaven be gathered together
34 unto one place, and let the dry land appear: and it was so.
35 — Genesis 1:9
37 And God called the dry land Earth; and the gathering together of
38 the waters called he Seas: and God saw that it was good.
39 — Genesis 1:10
41 And God said, Let the earth bring forth grass, the herb yielding
42 seed, and the fruit tree yielding fruit after his kind, whose seed
43 is in itself, upon the earth: and it was so.
44 — Genesis 1:11
It is worthy mentioning the same opeartion can be achieved with good old /bin/cat with cat -n, e.g.;
$ cat -n bible >bible_quotes_numbered.txt
On *BSDs nl command is not available, thus cat -n is very good to know of since it works for numbering ASCII plain text files on Free/Net/OpenBSDs