1

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.

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
uliaison
  • 13
  • 2

2 Answers2

5

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.

galfisher
  • 1,122
  • 1
  • 13
  • 24
2

You can use nl from the GNU coreutils to number your lines:

nl -w 3 -n rz -s ' ' infile
  • -w (--number-width) says how many columns to reserve for the line number
  • -n (--number-format) says how to format the number; rz is "right justified, leading zeros"
  • -s (--number-separator) is the string to insert between the number and the line itself; in this case, a space

This defaults to skipping empty lines:

$ nl -w 3 -n rz -s ' ' infile
001 Lorem ipsum dolor sit amet consectetur adipiscing elit
002 sed do eiusmod tempor incididunt ut labore et

003 dolore magna aliqua Ut enim ad minim veniam
Benjamin W.
  • 46,058
  • 19
  • 106
  • 116