Using awk: Adding line numbers to a program

There might be times when you want to add line numbers to a program, for whatever reason. Maybe you want to post the program somewhere, or just print it out. You could do it by hand, but why when Unix provides the simplest of tools to do it – awk. Here is the code (where filename is the file to be processed):

awk '{printf "%d\t%s\n", NR, $0}' < filename

Basically all this does is process ever line of the file, printing out the result to standard output. The is done by printf using the string “%d\t%s\n“. The %d specifies that the first thing to be printed will be an integer, in this case NR, which is a built-in variable that stands for “number of records”. Each line is a record, so the value printed will be the line number. The \t inserts a tab in the output. The %s prints out a string, in this case $0, which represents the entire line of input. The \n inserts a newline in the output. So below is the input and output for a Pascal program.

program factorial;

var i, n, fact : integer;

begin
    writeln('Enter a number: ');
    read(n);
    fact := 1;
    for i := 2 to n do
        fact := fact * i;
    write(n,'! = ', fact);
end.
1	program factorial;
2
3	var i, n, fact : integer;
4
5	begin
6	    writeln('Enter a number: ');
7	    read(n);
8	    fact := 1;
9	    for i := 2 to n do
10	        fact := fact * i;
11	    write(n,'! = ', fact);
12	end.

Obviously to move the result to a file, just redirect the output.

Advertisement

One thought on “Using awk: Adding line numbers to a program

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.