Posts Tagged ‘ascii text files’

Add line numbering to text file with prefix text on Linux with awk

Monday, March 25th, 2013

 

Recently I blogged a tiny article on how to add line numbering to ASCII text files with nl cmd. Today I needed to do the same line numbering, except I wanted to add a prefix text "R0" to each line number to match requirements of program which will later take use of .txt database file. I looked through nl (number lines) command manual but didn't find option with which I can insert a prefix string to each numbered line. I'm not a regular expression GURU, thus I asked for some help in irc.freenode.net on how to do it. Thanks to the kind guys in #bash I got it.

Here is how to add line numbering starting from 01onwards by adding a text prefix "R0":

$ awk '{ printf "R0%02d %s\n", NR, $0 }' text_file_to_number.txt > numbered_text_file_with_prefix.txt

The file to number in my case included a huge text file containing verses from Holy Bible, here is few lines from it before and after parsing and numbering with string prefix:

 

In the beginning God created the heaven and the earth.
                — Genesis 1:1
%
And the earth was without form, and void; and darkness was upon
the face of the deep. And the Spirit of God moved upon the face of
the waters.
                — Genesis 1:2
%
And God said, Let there be light: and there was light.
                — Genesis 1:3
 

 

R001 In the beginning God created the heaven and the earth.
R002            — Genesis 1:1
R003 %
R004 And the earth was without form, and void; and darkness was upon
R005 the face of the deep. And the Spirit of God moved upon the face of
R006 the waters.
R007            — Genesis 1:2
R008 %
R009 And God said, Let there be light: and there was light.
R010            — Genesis 1:3

 

 

To add any other prefix except R0 for example SAMPLE_PREFIX_STRING, substitute in above awk expression R0 with whatever expression;

 

awk '{ printf "SAMPLE_PREFIX_STRING%02d %s\n", NR, $0 }' text_file_to_number.txt > numbered_text_file_with_prefix.txt