Add Line Numbers to a Text File

I am working on building a list of character states for a possible phylogenetic analysis of this small corpus of legends I have. As I go through the legends and add character states, essentially plot elements (a lot like motifs), I am writing lines like this:

Spirit Controller: [0] absent [2] present
Spirit: [0] absent [1] pirate [2] bull [3] dog [4] wind

Each state/motif needs to be numbered (eventually) so that each text can be described using this list. As I work through the texts, however, I find I am regularly re-ordering the list. At first, I was re-ordering by hand, but I (eventually) realized that I could leave the numbering for later, once I had arrived at a satisfactory sequence.

There are a couple of options for numbering the lines in a text file: cat, nl, and awk, with nl being expressly for the purpose. First, nl:

nl -ba -s ': ' filename > filenamenumbered

Then cat:

cat -n file > file_new

And, finally, awk:

awk '{printf("%5d : %s\n", NR,$0)}' filename > filenamenumbered

Leave a Reply