uliaison uliaison - 2 months ago 13
Linux Question

awk - using printf to format only one field of output?

A very basic query, but one which I haven't been able to resolve. I am a very basic awk user.

I wish to take a file (no more than 100 records) into awk, and output the file modified only by adding a line number (0 padded) at the start of each line.

Thus, input file:

Lorem ipsum dolor sit amet consectetur adipiscing elit
sed do eiusmod tempor incididunt ut labore et

dolore magna aliqua Ut enim ad minim veniam
...


Output file:

001 Lorem ipsum dolor sit amet consectetur adipiscing elit
002 sed do eiusmod tempor incididunt ut labore et
003
004 dolore magna aliqua Ut enim ad minim veniam
...


My little one liner to do the line numbering goes (rather obviously)

awk '{print NR, $0}' *infile*


From which I get

1 Lorem ipsum dolor sit amet consectetur adipiscing elit
2 sed do eiusmod tempor incididunt ut labore et
3
4 dolore magna aliqua Ut enim ad minim veniam
...


Note that the input file has blank records which need to be preserved (but would be better output unnumbered)

I also know that I can do

awk '{printf "%03i", NR}' infile


to give me

001
002
003
...


What I can't see is how to combine the two.

I'm using awk/gawk 4.0.1 on Linux, so the the rest of the usual Linux toolbox is available to me if there are alternate ways of doing what I want.

Answer

You can use printf to print the number and then the content:

awk '{printf "%03i %s\n", NR, $0}' *infile*

03i will print the line number - NR and %s will print the current line - $0. The rest is formatting - need to add space between the both and \n for a line break between every line.

Comments